[英]Unable to alert a json object after a ajax call
I have a php file with an array that has a few values. 我有一个带有几个值的数组的php文件。 I also have a html page with a single input field. 我也有一个带有单个输入字段的html页面。 I have a listener that listens for changes in the input field, when a change happens a ajax call is made to the php file with an array. 我有一个侦听器,用于侦听输入字段中的更改,当发生更改时,会对具有数组的php文件进行ajax调用。 The php file uses json_encode() to convert the array to json. php文件使用json_encode()将数组转换为json。
Once this is done the data is returned to my html page and I am trying to alert the data. 完成此操作后,数据将返回到我的html页面,并且我正在尝试提醒数据。
However I am not able to, I get no errors, simply nothing happens and I am not sure why. 但是我不能,没有错误,只是什么也没发生,我不确定为什么。
Here is my code. 这是我的代码。
<input type="text" name="searchDB" id="searchDB" placeholder="Type Address Here" autofocus=""/>
<script>
$(document).ready(function(){
$("#searchDB").change(function(){
$.ajax({
type:"GET",
url: "request_9_dnm_db.php",
data: "hi="+$("#searchDB").val(),
dataType: "json",
success:function(msg){
var obj = jQuery.parseJSON(msg);
alert(obj.name);
}//Success
});//Ajax Call
});//SearchDB Change
});//document.ready
</script>
And Here is my php 这是我的PHP
<?php
$boom = array("user"=>array( array(
"name"=>"Bob",
"last"=>"Smith"), array(
"name"=>"Jon",
"last"=>"Snow"
)
)
);
$coded = json_encode($boom);
return $coded;
You are using return
in PHP in a wrong place. 您在错误的地方使用了return
in PHP。 Give this instead: 给这个代替:
echo $coded;
The above code should be used instead of return $coded;
应该使用上面的代码而不是return $coded;
. 。
You are already added dataType: "json"
so you don't need to parse it again using var obj = jQuery.parseJSON(msg);
您已经添加了dataType: "json"
因此无需使用var obj = jQuery.parseJSON(msg);
再次解析它var obj = jQuery.parseJSON(msg);
$.ajax({
type:"GET",
url: "request_9_dnm_db.php",
data: "hi="+$("#searchDB").val(),
dataType: "json",
success:function(obj){
alert(obj.name);
}//Success
});//Ajax Call
Also in your php you need to echo the json encoded string instead of returning 另外在您的php中,您需要回显json编码的字符串,而不是返回
echo $coded;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.