将数据从javascript发送到php文件

Sending data from javascript to php file

本文关键字:php 文件 数据 javascript      更新时间:2023-09-26

我有这个函数从服务器上的php文件中获取文本,并将其放入HTML页面。

我需要做什么改变,以发送数据(只是一对javascript变量)到php文件,而不是从它读取?希望不要太多!!

function process() {
  if (xmlHttp) // the object is not void
  {
    try {
      xmlHttp.open("GET", "testAJAX.php", true);
      xmlHttp.onreadystatechange = handleServerResponse;
      xmlHttp.send(null);
    } catch (e) {
      alert(e.toString());
    }
  }
}

看看你可以使用哪些标题。在您的情况下,您可能希望使用POST而不是GET

 xmlHttp.open("POST", "testAJAX.php", true);
 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//or JSON if needed
 xmlHttp.onreadystatechange = handleServerResponse;
 xmlHttp.send(data);

您最好使用POST发送数据,因为它的限制较少。例句:

var data = {
    user: 'Joe',
    age: 12
};
var httpReq = new XMLHttpRequest();
// true means async - you want this.
httpReq.open('POST', 'testAJAX.php', true);
// json is just a nice way of passing data between server and client
xmlhttpReq.setRequestHeader('Content-type', 'application/json');
// When the http state changes check if it was successful (http 200 OK and
// readyState is 4 which means complete and console out the php script response.
httpReq.onreadystatechange = function () {
    if (httpReq.readyState != 4 || httpReq.status != 200) return; 
    console.log(httpReq.responseText);
};
httpReq.send(JSON.stringify(data));

并阅读它:

$name = json_decode($_POST['name']);
$age = json_decode($_POST['age']);

如果只有几个变量,可以将它们放入查询字符串中—尽管您需要确保它们的值不会破坏PHP脚本或打开安全漏洞(例如,不要将用户输入解释为SQL字符串)。对于更复杂的数据结构,可以像其他人建议的那样使用POST。

function process(var1value, var2value) {
    if(xmlHttp) {
        try {
           xmlHttp.open("GET", "testAJAX.php?var1="+var1value+"&var2="+var2value, true);
           xmlHttp.onreadystatechange = handleServerResponse;
           xmlHttp.send(null);
        } catch(e) {
           alert(e.toString());
        }
    }
}