<?php
// 第一种方法JSONP,JSONP只支持get请求
// 首先在jquery-ajax配置参数中添加这两项
dataType: "jsonp",
jsonp: "callback",
//例如
$.ajax({
type: "GET",
url: "http://127.0.0.1/ajax2/serverjsonp.php?number=" + $("#keyword").val(),
dataType: "jsonp",
jsonp: "callback",
success: function(data) {
if (data.success) {
$("#searchResult").html(data.msg);
} else {
$("#searchResult").html("出现错误:" + data.msg);
}
},
error: function(jqXHR){
alert("发生错误:" + jqXHR.status);
},
});
// 然后,在php中做修改
$jsonp = $_GET["callback"];
echo $jsonp . '({"success":false,"msg":"参数错误"})'; //输出的字符串前面要拼接上jsonp
// 跨域第二种方法XHR2,其他浏览器都支持,但是IE必须得IE10以上,只需要加上以下头信息
header('Access-Control-Allow-Origin:*'); //允许所有访问
header("Access-Control-Allow-Origin", "http://my.domain.cn:8080"); //只允许特定域名访问
header('Access-Control-Allow-Methods:POST,GET'); //允许跨域请求的方法,可以做限定
header('Access-Control-Allow-Credentials:true'); //请求的时候是否带上cookie信息
原文地址:https://blog.csdn.net/qq_42195688/article/details/80373222