6

我似乎无法弄清楚如何使用 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 />";
?>

我在萤火虫或 chrome 的工具中找不到任何问题。我做错了什么可以吗?

4

6 回答 6

6

整个问题是由您既提交表单又执行 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 />";
?>
于 2013-09-19T23:45:14.907 回答
3

这是我的做法:

在你的 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);
    }
  });
};
于 2013-09-19T23:35:57.873 回答
3

制作:

<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() 是一种不好的做法?因为无论如何您都将帖子包含在一个函数中。

编辑:我刚刚注意到您的标题和头部标签在您提供的来源中被破坏了。

于 2013-09-20T00:06:29.477 回答
0

也许你最好使用像 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 代码对于日常的实际使用将变得毫无用处.

于 2013-09-20T00:06:18.717 回答
0

你需要在函数结束时返回 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;
}
于 2013-09-19T23:41:21.537 回答
0

将帖子发送到同一层次结构中的 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/

于 2018-07-27T20:51:13.487 回答