Javascript 影响将PHP查询结果返回到HTML表单输入字段
主文件的内容Javascript 影响将PHP查询结果返回到HTML表单输入字段,javascript,php,html,ajax,Javascript,Php,Html,Ajax,主文件的内容 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <meta http-equiv="Content-Type" content="te
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test JSON</title>
<style type="text/css">
body {
margin : 100px;
}
h1 {
text-align: center;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$("#btn").click(getNewVal);
});
function getNewVal(){
var xhr = new XMLHttpRequest();
var queryString = "getVal.php?str=" + "Blah";
xhr.open("GET", queryString, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
//alert(document.getElementById("txtField").value);
var JSONObj = JSON.parse(xhr.responseText);
alert(JSONObj.item);
document.getElementById("txtField").value = JSONObj.item;
}
}
xhr.send(null);
}
</script>
</head>
<body>
<h1>Test JSON</h1>
<hr />
<form id="testForm" method="GET" action="">
<label>Custom Value: </label>
<input type="text" value="La valeur a changer" id="txtField">
<input type="submit" value="Bouton pour changer la valeur" id="btn">
</form>
</body>
测试JSON
身体{
利润率:100像素;
}
h1{
文本对齐:居中;
}
$(文档).ready(函数(){
$(“#btn”)。单击(getNewVal);
});
函数getNewVal(){
var xhr=new XMLHttpRequest();
var queryString=“getVal.php?str=“+”Blah”;
xhr.open(“GET”,queryString,true);
xhr.onreadystatechange=函数(){
if(xhr.readyState==4){
//警报(document.getElementById(“txtField”).value);
var JSONObj=JSON.parse(xhr.responseText);
警报(JSONObj.item);
document.getElementById(“txtField”).value=JSONObj.item;
}
}
xhr.send(空);
}
测试JSON
自定义值:
ajax调用文件的内容
<?php
if (mysqli_connect_errno())
{
echo "Problème avec la connection : " . mysqli_connect_error();
}
else{
if(isset($_GET['str'])) {
$val = $_GET['str'];
$post_data = array('item' => $_GET['str']);
echo json_encode($post_data);
}
else{
echo "error";
}
}
?>
我想返回查询结果并将其影响到另一个php文件中的html文本输入字段。在对JSON进行更改之后,除了document.getElementById(“txtField”).value=JSONObj.item之外,其他一切都正常工作。我错过了什么
提前谢谢 与当前的echo
行不同,只需以JSON或其他基本格式回显查询的$result
。在你的JS代码中,解析响应并使用它来更改你的
。谢谢Chris,我已经编辑了我的上一篇文章来反映当前的问题,如果你有时间看一下,我将非常感谢。谢谢“不起作用”不是一个有用的问题描述。我假设警报()
正在发生并显示返回的数据?你有没有检查控制台有没有错误?这是一个处理虚拟请求的工作程序:(我将处理程序更改为处理表单提交并返回false)