![](/img/trans.png)
[英]how to display response text as html and at the same time send to a php page
[英]How to display response from PHP on HTML page?
我在HTML页面上有一个文本字段和一个按钮。 还有一个para标签,它将在验证时显示错误。
如果该字段为空,则将其更改为Name must be filled out
并正在更改为验证。
现在,当我输入一个字符串并按下提交按钮时。...该值应传递到PHP页面并检查条件并在HTML页面上相应地打印消息...但是当我单击“提交”时,该消息就会打印在index.php页面本身。
我应该如何使用AJAX代码,以便将消息在id标记为para的错误消息上打印出来?
请帮忙。 提前致谢。
HTML代码
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script type="text/javascript" src="java123.js"></script>
</head>
<body>
<form action="index.php" method="post" onsubmit="return validateForm()">
<input type="text" name="name" id="name">
<input type="submit">
</form>
<p id="error"></p>
</body>
</html>
PHP代码
<?php
$name = $_POST['name'];
if($name == "thistext"){
$arr = array("sth"=>"hello");
echo json_encode($arr);
}else{
$arr = array("sth"=>"User does not exist");
echo json_encode($arr);
}
?>
JAVASCRIPT代码
var invalid = 0;
function validateForm() {
/* WHERE SHOULD I PUT THIS CODE
$.ajax({
url: "index.php",
type: "POST",
dataType: "json",
success: function(response) {
$("#error").html(response.sth);
}
});
*/
invalid = 0;
name = document.getElementById("name").value;
if(name == ""){
document.getElementById('error').innerHTML = "Name must be filled out";
invalid = 1;
}else{
document.getElementById('error').innerHTML = "";
}
if(invalid != 0){
return false;
}else{
return true;
}
}
function validateForm() {
invalid = 0;
name = document.getElementById("name").value;
if(name == ""){
document.getElementById('error').innerHTML = "Name must be filled out";
invalid = 1;
}else{
document.getElementById('error').innerHTML = "";
}
if(invalid != 0){
$.ajax({
url: "index.php",
type: "POST",
dataType: "json",
success: function(response) {
$("#error").html(response.sth);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}
}
尝试这个
function validateForm() {
var name = $('name').value;
if(name == ""){
$('error').innerHTML = "<b>Name must be filled out</b>";
// you need to send data also
$.ajax({
url: "index.php",
type: "POST",
dataType: "json",
data: { 'name': name },
success: function(res) {
// $("#error").html(res.sth);
console.log(res);
},
error: function(err){
console.log(err);
}
});
}else{
$('error').innerHTML = "";
}
/* Always return false because this will prevent actual form submit.
You are submitting form with ajax.
*/
return false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.