如何在HTML页面上显示PHP的响应
How to display response from PHP on HTML page?
我在HTML页面上有一个文本字段和一个按钮。还有一个para标签,它将在验证时显示错误。
如果字段为空,它将被更改为Name must be filled out
并在验证时更改为
现在当我输入一个字符串并按下提交按钮....该值应该传递给PHP页面,并检查条件,并相应地在HTML页面上打印消息…但是当我点击提交的消息是打印在index.php页面本身。
我应该如何使用AJAX代码,使它打印与id错误的para标签上的消息?
请帮助。提前谢谢。
<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);
}
});
}
}
try this
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
}
相关文章:
- 如何使用JavaScript函数在网页中显示PHP变量
- 如何避免试图用php+jquery显示php起始页的无限循环
- 在Javascript代码中显示PHP数组变量
- 使用jquery和javascript显示PHP中的变量
- 显示php中的函数javascript
- 显示php中的加载百分比文本
- 如何在javascript中显示php
- 如何在刷新时显示PHP表单中的随机文本和图像
- 无法在javascript中显示php变量
- 按钮,显示 PHP 中表的选定行的完整信息
- 在另一个 PHP 文件的 JavaScript 中显示 PHP 文件内容
- 如果禁用了 js,如何显示 php 生成的网站
- 谷歌图表没有显示 PHP 中的 Ajax 调用
- 如何在表单旁边显示 php 表单验证错误
- 使用 ajax 显示 php 响应文本
- 在 Javascript 警报框中的新行上显示 PHP 数组的每个条目
- jquery显示php-json编码数组的值时出现未定义错误
- 通过jquery;显示php文件中的记录;
- 如何在基于JS的Google图表中显示PHP数组值
- 以 js 格式显示 php 数组