php + jquery ajax 跨域请求

来源:互联网 发布:最优化技术与数学建模 编辑:程序博客网 时间:2024/04/29 10:48

第一种解决方案,在请求地址头部加上:

//允许所有的域名跨域请求
header("Access-Control-Allow-Origin: *");

第二种方案:

getJSON:

                        $.getJSON("http://www.youdomain.com&jsonpCallback=?",function(json){
                            json = typeof json == "string" ? eval("("+json+")") : json;
                            if(json.status == 1){
                                alert(json.code);
                            }else{
                                alert(json.msg);
                            }
                        });

php :

调用以下方法:

/**
 * 处理返回JSON 自动判断是否需要跨域
 * @param array $arr 数据
 */
function arr2json( $arr ) {
$jsonStr = json_encode( $arr );
$callBack = $_GET['callback'];
if ( empty( $callBack ) ) $callBack = $_GET['jsonpCallback'];
if ( $callBack ) $jsonStr = "{$callBack}({$jsonStr})";
header( 'Content-type: application/json' );
echo $jsonStr;
exit;
}

0 0
原创粉丝点击