php 如何将ajax POST发送到php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18906547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to ajax POST to php
提问by include 'breakDance'
I can't seem to figure out how to use ajax to post. I made a silly form to try it out and even after having cut it all the way down to just two values, still can't get anything to work. My html is this:
我似乎无法弄清楚如何使用 ajax 发布。我做了一个愚蠢的表格来尝试一下,即使将它一直削减到只有两个值,仍然无法得到任何工作。我的 html 是这样的:
<html>
<head>
<script type="text/javascript" src="j.js"></script>
<title>Test this<
<body>/title>
</head>
<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="submit" value="Submit Form" />
</form>
<div id="status"></div>
</body>
</html>
Then, my external javascript is just a single function so far:
然后,到目前为止,我的外部 javascript 只是一个函数:
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "processForm.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
While my php just echoes the stuff back:
虽然我的 php 只是回应了这些东西:
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>
I can't find anything wrong in firebug or in chrome's toolsy thingies.. Can anybody who me what I'm doing wrong?
我在萤火虫或 chrome 的工具类东西中找不到任何问题。任何人都知道我做错了什么吗?
采纳答案by Arjun Kumar
Make the:
使:
<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /> <br />
Last Name: <input type="text" name="lname" id="lname" /> <br />
<input type="submit" value="Submit Form" />
</form>
into a button tag:
进入按钮标签:
<form name="testForm">
First Name: <input type="text" name="fname" id="fname" /> <br />
Last Name: <input type="text" name="lname" id="lname" /> <br />
<button type="button" onclick="postStuff();">Submit Form!</button>
</form>
The page refreshes from the form submit as far as I can see. You don't need to use a form if you're using ajax.
据我所知,页面从表单提交刷新。如果您使用 ajax,则不需要使用表单。
Also read: Why is using onClick() in HTML a bad practice?since you're enclosing the post in a function anyway.
另请阅读:为什么在 HTML 中使用 onClick() 是一种不好的做法?因为无论如何您都将帖子包含在一个函数中。
EDIT: I just noticed your title and head tags are broken in the source you've put up.
编辑:我刚刚注意到你的标题和头部标签在你提供的来源中被破坏了。
回答by davidkonrad
The whole problem is caused by the fact that you are both submitting the form andperforming an AJAX call! status
is for sure updated, but in the same moment the page is refreshed (notice that the <input>
-values disappear)
整个问题是由您提交表单并执行 AJAX 调用这一事实引起的!status
肯定会更新,但在同一时刻页面被刷新(注意<input>
-values 消失了)
Simply avoid the form submit by altering the markup,
只需通过更改标记来避免表单提交,
<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />
and your code works. Or dont use a form at all. It is to no use when you are AJAXing anyway.
并且您的代码有效。或者根本不使用表格。无论如何,当你使用 AJAX 时它是没有用的。
update
更新
I reproduced the whole scenario before answering :
我在回答之前复制了整个场景:
xhr.html
xhr.html
<html>
<head>
<title>Test this</title>
</head>
<body>
<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />
</form>
<div id="status"></div>
<script>
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "xhr.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
console.log(hr);
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</body>
</html>
xhr.php
php文件
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>
回答by TDrabas
Here's how I do it:
这是我的方法:
In your html file put <SCRIPT type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></SCRIPT>
在你的 html 文件中放入 <SCRIPT type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></SCRIPT>
Then you can call this function that will call (in my case) queryDB.php
script.
然后你可以调用这个函数来调用(在我的例子中)queryDB.php
脚本。
function queryDB(db,query,doAfter){
$.ajax({
type: 'POST',
data: { host: "localhost",
port: "5432",
db: db,
usr: "guest",
pass: "guest",
statemnt: query
},
url: 'scripts/php/queryDB.php',
dataType: 'json',
async: false,
success: function(result){
// call the function that handles the response/results
doAfterQuery_maps(result,doAfter);
},
error: function(){
window.alert("Wrong query 'queryDB.php': " + query);
}
});
};
回答by Ryosuke Hujisawa
Send post to test.php in the same hierarchy and accept the result in html variable
将帖子发送到同一层次结构中的 test.php 并在 html 变量中接受结果
$.ajax(
{
type: "POST",
url: "test.php",
data: {'test': test, 'name': 0, 'asdf': 'asdf'},
success: function(html)
{
alert(html);
}
});
In PHP of the recipient, specify it as follows
在收件人的PHP中,指定如下
<?php
echo "come here";
echo $_POST['test'];
?>
Directory structure
目录结构
$ tree
.
├── a.php
└── test.php
回答by ias
u need to return false at the end of the function.
你需要在函数结束时返回 false。
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "processForm.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
return false;
}
回答by Neo
Perhaps it's best for you to use a library like jquery and then you can do something like : $('form').submit(function(){$.post('detinatnion', $('form').serialize());});
but to answer your question since you have a reason for using pure js then:
也许最好使用像 jquery 这样的库,然后您可以执行以下操作:$('form').submit(function(){$.post('detinatnion', $('form').serialize());});
但是要回答您的问题,因为您有理由使用纯 js:
<form method="post" action="pathToFileForJsFallback.">
First name: <input type="text" id="fname" name="fname" /> <br />
last name: <input type="text" id="lname" name="lname" /> <br />
<input type="submit" value="Submit Form" />
<div id="status"></div>
</form>
JS:
JS:
function postStuff(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
mypostrequest = new ActiveXObject(activexmodes[i]);
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
mypostrequest = new XMLHttpRequest();
else
return false;
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var fname=encodeURIComponent(document.getElementById("fname").value);
var lname=encodeURIComponent(document.getElementById("lname").value);
var parameters="fname="+fname+"&lname="+lname;
mypostrequest.open("POST", "destination.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
}
Again my recommendation to you is to learn js with a library like jquery, because by the time you learn how to do these stuff, these libraries, hardware and everything will be so fast that javascript code like this will become useless for practical every day use.
我再次给你的建议是使用像 jquery 这样的库来学习 js,因为当你学会如何做这些东西时,这些库、硬件和一切都会变得如此之快,以至于像这样的 javascript 代码对于日常使用将变得毫无用处.