前端

跨域请求问题+headers 设置+php处理方式

2019-05-14  本文已影响16人  端木安玉

解决跨域调用服务并设置headers 主要的解决方法需要通过服务器端设置响应头、正确响应options请求,正确设置 JavaScript端需要设置的headers信息 方能实现。

方法一 服务端设置响应头

header('Access-Control-Allow-Origin:*'); //支持全域名访问,不安全,部署后需要固定限制为客户端网址

header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); //支持的http 动作

header('Access-Control-Allow-Headers:x-requested-with,content-type'); //响应头 请按照自己需求添加。

方法二:一顿百度,可以用jsonp解决,具体方法步骤如下

(function($){
$.ajax({
        type: "post",
        url: "http://localhost:8022/test.json",
        data: $.toJSON(userData),
        dataType: 'jsonp',
        jsonpCallback:'callback',
        success: function(result) {
            alert(result);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest.status);
            alert(XMLHttpRequest.readyState);
            alert(textStatus);
        }
    });
})(jQuery)
上一篇 下一篇

猜你喜欢

热点阅读