简体   繁体   English

AJAX将POST变量发送到PHP

[英]AJAX Send POST Variables to PHP

I am used to sending AJAX requests with jQuery. 我习惯用jQuery发送AJAX请求。 I now find myself with the task of having to send them using 'vanilla' JS. 现在,我发现自己必须使用“ vanilla” JS发送它们。 Using my limited knowledge, I managed to get everything working except for passing the data along with the request. 利用我有限的知识,除了将数据与请求一起传递外,我设法使一切正常。 The two variables that are supposed to be being passed along are always filled in as NULL in my database. 应该传递的两个变量在我的数据库中始终以NULL填充。 Every example I have been able to find on here shows the jQuery way, which I have no problem doing. 我在这里可以找到的每个示例都显示了jQuery的方式,我这样做没有问题。

Can anyone tell me what I am doing wrong? 谁能告诉我我在做什么错? I assume it has something to do with the format of the data, but cannot for the live of me figure it out. 我认为它与数据的格式有关,但我无法实时了解它。

Here is the code for the request. 这是请求的代码。 The request object is built in the createXMLHttp() function. 请求对象内置在createXMLHttp()函数中。

var xmlHttp = createXMLHttp();
var data = {Referrer: document.referrer, Path: window.location.pathname};
xmlHttp.open('post', '/PagePilotSiteHits.php', true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(data);
 var data = {Referrer: document.referrer, Path: window.location.pathname};

 function buildQueryString(data)
 {
     var dataKeys = Object.keys(data);
     var queryString = "";
     for (var i = 0; i < dataKeys.length; ++i)
     {
         queryString += "&" + dataKeys[i] + "=" + encodeURICompenent(data[dataKeys[i]]); 
     }
     return queryString.substr(1);
 }

 xmlHttp.send(buildQueryString(data));

This should do it. 这应该做。 The data needs to be passed as a querystring . 数据需要作为querystring传递。 This functions will create a querystring from the data object you've provided and encodes the uri components as mentioned by @AlexV and @Quentin. 此函数将根据您提供的数据对象创建查询字符串,并对@AlexV和@Quentin提到的uri组件进行编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM