簡體   English   中英

如何在AJAX請求中使用GET調用PHP文件?

[英]How can I call a PHP file with GET on an AJAX request?

我試圖從AJAX請求中分配了GET參數的PHP文件中獲取數據:

xmlhttp.open( “GET”, “?getMyData.php NAME =” +名字+ “和電子郵件=” +電子郵件,真實);

我可以這樣調用getMyData.php,還是必須在項目的根目錄中? 現在與javascript文件位於同一目錄中。

此外,如果可能,還有一個如何將返回的數據插入輸入字段的小示例。

謝謝你!

這里的例子

var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
  //xmlhttp.responseText; //content 
  document.getElementById("myDiv").innerHTML=xmlhttp.responseText; //write inside myDiv
}
}
xmlhttp.open("GET","getMyData.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name="+name+"&email="+encodeURIComponen(email));
xmlhttp.send();
}

看這里獲取更多信息和示例

看看相對和絕對的路徑 您將了解/../等是如何工作的。 如果PHP文件與執行javascript的網頁位於同一文件夾中,您還會看到您的示例是正確的。

關於最后一部分,我正在切斷一些代碼(例如你可以在這里完全找到),但這里有一點:

if (xhr.readyState === 4 && xhr.status === 200) {
    // The datas returned by PHP are in the variable 'xhr.responseText' or 'xhr.responseXml'.
    // In this case you can add straight the HTML into a DIV, but you usually have datas in JSON.
    // To "transform" your JSON string into a javascript object, use the following:
    //     var obj = JSON.parse(xhr.responseText)
    document.getElementById("myDiv").appendChild(xhr.responseXml) // Don't use 'innerHTML', it is evil.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM