簡體   English   中英

如何ajax POST到PHP

[英]How to ajax POST to php

我似乎無法弄清楚如何使用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>

然后,到目前為止,我的外部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...";
}

雖然我的PHP只是回復了這些東西:

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>

我在firebug或者chrome的工具中找不到任何錯誤..任何人,我是誰,我做錯了什么?

整個問題是由於您提交表單執行AJAX調用而引起的! status肯定會更新,但在同一時刻刷新頁面(請注意<input> -values消失)

只需通過更改標記來避免提交表單,

<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();" />

並且您的代碼有效。 或者根本不使用表格。 無論如何,當你使用AJAX時都沒用。


更新

在回答之前我復制了整個場景:

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
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>

我是這樣做的:

在你的html文件中<SCRIPT type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></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);
    }
  });
};

制作:

<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>

進入按鈕標簽:

<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>

就我所見,頁面從表單提交刷新。 如果您使用的是ajax,則無需使用表單。

另請閱讀: 為什么在HTML中使用onClick()是一種不好的做法? 因為無論如何你都把帖子放在一個函數中。

編輯:我剛剛注意到你的標題和標題在你提出的來源中被破壞了。

你需要在函數結束時返回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;
}

也許你最好使用像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:

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);

}

我的建議再一次是用jquery這樣的庫學習js,因為當你學習如何做這些東西時,這些庫,硬件和一切都會如此之快,以至於這樣的javascript代碼對於實際的日常使用都會變得無用。

將帖子發送到同一層次結構中的test.php並接受html變量中的結果

$.ajax(
{
type: "POST",
url: "test.php",
data: {'test': test, 'name': 0, 'asdf': 'asdf'},

success: function(html)
{
alert(html);
}
});

在收件人的PHP中,請按如下所示進行指定

<?php 
echo "come here";
echo $_POST['test'];
?>

目錄結構

$ tree
.
├── a.php
└── test.php

參考https://off.tokyo/blog/ajax%E3%81%A7post%E3%82%92%E5%8F%97%E3%81%91%E5%8F%96%E3%82%8B%E6 %96%B9%E6%B3%95 /

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM