[英]How do you submit a form , make new text pop up and stay on the same page?
[英]How do you make the response of an HTML form update the text on a page?
我有一個HTML形式,如下所示。 我正在嘗試使該POST的響應(字符串)成為帶有id =“ answer”的文本。
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"> </script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script src="form.js"></script>
</head>
<body>
<form id="myForm"
action="http://myserver.com/post-destination/"
method="post">
<p><label>Input: <br><textarea name="formInput"></textarea></label></p>
<p><input type="submit" value="Submit" /></p>
</form>
<p id="answer">?</p>
</body>
我正在嘗試在名為form.js的文件中使用jQuery Form插件,該文件包括:
$(document).ready(function() {
$('#myForm')
.ajaxForm({
target: "#answer"
});
});
我在這里做錯了什么? 我敢肯定這只是一個愚蠢的東西,而且我知道關於HTML表單和jQuery的問題很多,但事實證明,遵循它們是不成功的。 我只是想不通,因為這是我第一次嘗試任何與網絡相關的事情。 謝謝您的幫助!
您可以嘗試以下方法:
<head>
<script>
function text() {
var answer = document.getElementById("input").value;
document.getElementById("answer").innerHTML = answer;
}
</script>
</head>
<body>
<form id="myForm" action="http://myserver.com/post-destination/" method="post">
<p><label>Input: <br><textarea id="input" name="formInput"></textarea></label></p>
<p><input onClick="text()" type="submit" value="Submit" /></p>
</form>
<p id="answer">?</p>
</body>
您的jQuery ajax調用似乎不正確。 您可以按以下方式重構它:
$(document).ready(function() {
$('#myForm').submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
// set the target data
console.log ('set the target data');
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
console.log ('server responded something else ...');
}
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.