将数据从javascript发送到php文件
Sending data from javascript to php file
我有这个函数从服务器上的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());
}
}
}
相关文章:
- 如何在php文件中获取$.post-ajax传递的值
- Javascript运行php文件,然后下载文件
- 通过Ajax将JavaScript函数传递给PHP文件
- 我想使用模态通过php文件发送邮件,并且我希望在提交关闭后关闭pop
- 通过ajax到php文件获取单选按钮值
- 每天用javascript包含不同的php文件
- 如何使用javascript调用Php文件
- 如何使用php文件中的GET来获取我在.js文件中声明的变量
- 在CodeIgniter视图中将Javascript或jQuery代码作为PHP文件编写可以吗
- 从表单中动态生成一个字符串,传递给通过AJAX加载的PHP文件
- 包括php文件和几个js文件
- 将JavaScript变量传递到HTML输入框和(在PHP文件中使用)
- PHP文件没有't从Javascript应用程序获取$_POST
- 如何显示由ajax调用运行的PHP文件的echo
- 如何将php变量从php文件传递到js文件
- 如何使用javascript/jquery将变量从一个PHP文件传递到另一个PHP文件
- 在同一主机上对PHP文件使用XMLHTTP请求的Javascript违反了同源策略
- 通过Wordpress中的jquery调用运行php文件
- 通过Javascript调用php文件
- 如果($_SERVER[“REQUEST_METHOD”]=“POST”)条件在ajax调用不同的php文件进行验证和提