问题描述
我有以下的code,搜索键入搜索框的onkeyup事件的人物。
I have the following code that searches the characters typed in the search box with the onkeyup event.
$("#keywords").keyup(function () {
var kw = $("#keywords").val();
if (kw != '') {
var url = "<?php echo base_url().'index.php/simpromotions/livesearch/';?>" + kw;
$.ajax({
type: "POST",
url: url,
datatype: "json",
success: function (data) {
**alert(data);**
$.each(data,function(ptitle, category){
$("#results").html('<label>'+ptitle+': '+category+'</label><br>');
}
}
});
}else{
$("#results").html("");
return false;
}
});
在时,我提醒数据上面的code
这里显示以下数组字符串。
In the above code when I alert the data
it displayes the following array string.
{"pcode":"22","category":"NightTalk","ptitle":"HourlyNightTalk"}
我似乎无法访问点code
,类
和 ptitle
因为我已经做了下一行。 (后警报)请帮我,我怎么能访问这三个!
I cant seem to access the pcode
, category
and ptitle
as I have done in the next line. (after alert)Please help me how I can access the three!
推荐答案
这意味着数据
是一个字符串,并且响应是一个简单的JSON恩codeD对象,不是阵列
That means data
is a string, and the response is a simple JSON encoded object, not an array.
您必须首先解析响应。你可以让jQuery的通过固定的dataType
属性为你做这个:
You have to parse the response first. You can let jQuery do this for you by fixing the dataType
property:
dataType: "json" // dataType, not datatype
在回调,数据
将是一个JavaScript对象,现在,你只需要直接访问其属性(了解更多关于的):
Inside the callback, data
will be a JavaScript object now and you just directly access its properties (learn more about objects in MDN - Working with Objects):
success: function (data) {
$("#results").html('<label>'+data.ptitle+': '+data.category+'</label><br>');
}
这是没有意义的使用 $。每个
在这里。 看一看文档了解它做什么以及它是如何工作的。
It doesn't make sense to use $.each
here. Have a look at the documentation to learn what it does and how it works.
您提到,有时候,你实际上得到一个数组回来。在这种情况下,你可能想使用 $。每个
。为了让您的code简单,我建议为总是从服务器返回一个数组:
You mentioned that sometimes you actually get an array back. In that case you probably want to use $.each
. To make your code simpler, I recommend to always return an array from the server:
var $results = $('#results');
$results.empty();
$.each(data, function(i, obj){
$results.append('<label>'+obj.ptitle+' is in '+obj.category+'</label><br>');
});
这篇关于我怎么访问的jQuery AJAX函数返回的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!