在处理一个简单项目的过程中(或者至少我认为很简单),用户单击一个按钮,从 php 生成的随机语句出现在上面的文本框中。我无权访问 php 文件,因此看不到代码,感觉有点失落。我相信我遇到的问题是处理服务器响应(handleServerResponse 函数)的方式出现错误。任何建议将不胜感激。
在尝试调试时,我看到了此消息:(我已更改网址)
XMLHttpRequest cannot load http:somephp.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
到目前为止的代码:
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Error 1");
else
return xmlHttp;
}
$("#BtnReset").click(function () {
$("#TBSaying").val("");
})
$("#BtnGetSaying").click(function () {
process();
})
function process(){
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
xmlHttp.open("GET", "http://somephp.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data
$("#TBSaying").val(message);
}else{
alert('error 2');
}
}
}
通读 JQuery 文档并重新开始,将其上传到 php 所在的同一服务器并运行。这是最终代码:感谢所有建议!
$("#BtnReset").click(function () {
$("#TBSaying").val("");
})
$("#BtnGetSaying").click(function () {
process();
})
function process(){
// AJAX Code To Submit Form.
$.get("http://somephp.php",function(data){
$("#TBSaying").val(data);
});
}
最佳答案
来自浏览器的 Ajax 调用受到所谓的“同源限制”的限制。基本上这意味着,默认情况下,您只能对网页来自的同一服务器进行 Ajax 回调。这意味着您无法对另一个域、端口或协议(protocol)上的服务器进行常规 Ajax 调用。
您可以阅读同源政策here .
有三种方法可以解决此限制,但都需要服务器的配合。
CORS。您发出请求的服务器会在其响应中放入 header ,告诉浏览器是否允许跨源请求,甚至允许来自哪些域。这使浏览器有权完成非同一来源的 Ajax 调用。
JSONP。您可以阅读有关 JSONP here 的更多信息。 。基本上,您从目标服务器请求一个脚本,该脚本的编码方式将为您提供所需的答案(通常采用 JSON 数据格式)。
服务器代理。您找到或编写了一个服务器代理,它将为您从其他服务器请求数据。由于服务器到服务器的通信不受同源限制,因此您有时可以找到另一台允许跨源请求的服务器,然后该服务器将为您获取数据,然后将其返回给您。
关于javascript - 处理服务器响应 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26900938/