我正在使用此代碼從php文件中獲取一些數據。該PHP文件有非常簡單的編碼,我已檢查它是否有效地工作。它看起來像是我的JavaScript代碼中沒有發送請求的錯誤。我的AJAX代碼下面貼:Ajax請求不會觸發。爲什麼?
var jax=new XMLHttpRequest();
jax.onreadystatechange = function() {
if (jax.readyState == 4 && jax.status == 200)
alert(jax.responseText);
}
jax.open("GET","http://marked.byethost12.com/response.php?req=1&rnd="+Math.random(),true);
jax.send();
自PHP文件中的代碼是這樣的:
<?php
$request=$_GET["req"];
if($request=="1") //requesting the initiation of protocol
echo 'alert("hello. the protocol has been initiated!")';
else
echo "alert! error in req variable. variable not present or value is not 1";
?>
腳本的地址(包括子域,目錄等)是什麼?瀏覽器的開發人員控制檯中是否有任何錯誤? –
我正在使用本地硬盤上的腳本(ajax文件),未上傳到任何Web服務器。 Firefox的開發控制檯中的錯誤字符串會這樣讀取:***跨域請求被阻止:相同的源策略不允許讀取http://marked.byethost12.com/response.php?req=1&rnd=0.1276921559338826處的遠程資源。 (原因:缺少CORS頭'Access-Control-Allow-Origin')*** –
您可能遇到跨域問題。看看這個:http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain – Marks