我正在使用英特尔xdk构建跨平台移动应用程序,我需要从服务器上运行的php检索数据到我的javascript中……这是我的js代码

var meRequest;
meRequest = new XMLHttpRequest();
meRequest.onreadystatechange=function()
{
    if(meRequest.readyState==4)
    {
        alert("request sent");
        alert((meRequest.responseText));
    }
}

meRequest.open("GET", "http://127.0.0.1/my_queries_1.php",true);
meRequest.send();


这是我的PHP代码:

<?php
echo json_encode(500);
exit;
?>


当我从本地主机上运行它们时,这是可行的,即两个脚本都在服务器上,但是我不能使用它,因为对于该应用程序,js必须嵌入到移动应用程序中,而php脚本仍保留在服务器上...但是如果我在本地主机外部运行javascript文件,则会得到null的responseText。
请问我该如何处理?

最佳答案

因此,您需要跨域请求,我认为类似这样的方法应该适合您:

// (1)
var XHR = ("onload" in new XMLHttpRequest()) ? XMLHttpRequest : XDomainRequest;

var xhr = new XHR();

// (2) cross domain request
xhr.open('GET', 'http://anywhere.com/request', true);

xhr.onload = function() {
  alert( this.responseText );
}

xhr.onerror = function() {
  alert( 'error ' + this.status );
}

xhr.send();


服务器端还应通过生成特殊的响应头来允许此类请求:

HTTP/1.1 200 OK
Content-Type:text/html; charset=UTF-8
Access-Control-Allow-Origin: http://example.com

10-07 13:29
查看更多