简体   繁体   English

Ajax Post参数

[英]Ajax Post parameters

I have a script that posts data to a php script: 我有一个将数据发布到php脚本的脚本:

xhr.open("POST","processData.php");

And i am sending once piece of data to it: 我向它发送一次数据:

xhr.send(email);

How would a post multiple peice of data to the php scrip? 如何将多个peice数据发布到php scrip? Lets say i have the variable first and last name that i want to sent to be processed? 可以说我有要发送给我的变量名和姓氏以进行处理吗? I've tried this: 我已经试过了:

xhr.send(essay, firstName); xhr.send(essay,firstName);

But not sure what to do with it in the PHP script, do i use the usual $_POST['essay'] to collect the values? 但是不确定在PHP脚本中如何处理它,我是否使用通常的$ _POST ['essay']来收集值? what about encoding aswell? 那编码呢?

Thanks for you help. 感谢您的帮助。

You create an object, and send that: 您创建一个对象,并将其发送:

var obj = {
    essay: essay,
    firstName: firstName
};
xhr.send("data=" + JSON.stringify(obj));

On server side you get: 在服务器端,您得到:

json_decode($_POST['data']); //Gives you a standard object with fields essay and firstName

just create the querystring to pass along send() 只需创建querystring来传递send()

xhr.send("essay=" + encodeURIComponent(essay) 
          + "&firstname=" + encodeURIComponent(firstName));

About encodeURIComponent you can see th MDN reference : it could be necessary use it if your variables contain uncommon chars like spaces, ampersands and other 关于encodeURIComponent,您可以看到MDN参考 :如果您的变量包含空格,&符等其他不常见的字符,则可能需要使用它

Use JSON (Javascript Object Notation): 使用JSON(JavaScript对象表示法):

http://www.json.org/ http://www.json.org/

var data = new Object;
data.name = 'some name';
data.id = 123
xhr.send(JSON.stringify(data))

You can turn this into an identical php object with json_decode(). 您可以使用json_decode()将其转换为相同的php对象。 The JS engine on current browsers has the JSON methods built in, but older IE's (6, 7) do not, so you need to include this script to compensate: 当前浏览器上的JS引擎内置了JSON方法,但是较旧的IE(6、7)却没有,因此您需要包括以下脚本来补偿:

https://github.com/douglascrockford/JSON-js/blob/master/json2.js https://github.com/douglascrockford/JSON-js/blob/master/json2.js

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

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