跨域从Javascript到PHP

时间:2014-05-08 16:51:09

标签: javascript php jquery cross-domain

我必须从服务器A上的javascript向服务器B上的php文件发出请求。我可以访问这两个服务器。

但有些事情出了问题。我总是准备好状态0,状态0。

这是我尝试的最新事情:请告诉我我做错了什么。感谢。

服务器A:

$.ajax({
    type: "GET",
    url: 'http://server_B/request.php',
    data: form_data,
    dataType: 'json',
    success: function (resp) {
        alert("Successful");
        console.log("Response completed");
        console.log("resp is" + resp);
    },
    error: function (xhr, error) {
        console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
        console.log("responseText: " + xhr.responseText);
        alert("Error occurred.");
    }
});

服务器B: request.php

<?php
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

    # do the work and save it on $result array.
    print json_encode($result,true);
?>

1 个答案:

答案 0 :(得分:-1)

要在两个不同的域之间使用ajax,您必须使用jsonp

您可以在here

中找到更多帮助