获取ajax返回结果
ajax是异步的。通常我们在succee、error中获取到后台返回的数据。如果我们想在外面获取呢?这时就需要使用responseText了。
var rspTxt = $.ajax({
async:false,
cache:false,
type : "POST",
url : "<%=basePath%>test.action",
data : {
id: $("#id").val()
},
success : function(data) {
var status = data.status;
if('success' == status){
alert("成功!");
}else{
}
},
error:function(){
alert("失败!");
}
}).responseText;
if(typeof(rspTxt) != "undefined") {
var obj = JSON.parse(rspTxt);
if(obj.status == 'success') {
// 业务处理
}
}
access-origin
ajax如果跨域请求,会报错。即:相同主机不同端口、不同主机的访问。此种问题我们需要在服务器端进行配置
springmvc
以下是springmvc项目的处理方式:
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
springboot
以下是springboot项目的处理方式:
// 方式一
@RestController
@Api("测试ajax跨域")
@RequestMapping("ajaxdemo")
@CrossOrigin
public class TestHttpController {
// ...
}
// 方式二
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;
/**
* Created by Tony on 2017/8/1.
* Spring Boot支持跨域请求的JSONP数据.
*/
@ControllerAdvice(basePackages = {"com.cyf.uicomm"})
public class JSONPConfiguration extends AbstractJsonpResponseBodyAdvice {
public JSONPConfiguration() {
super("callback", "jsonp");
}
}
ajax请求页面刷新
ajax请求,发现页面闪烁以下,刷新。可以配置global: false
来解决
$.ajax({
global: false,
type : "POST",
url : "",
contentType: "application/json", //必须有
dataType: "json",
data: JSON.stringify(jsonData),
success : function(data) {
},
error : function() {
}
});