gpt4 book ai didi

jquery - Ajax 数据回调被视为文字

转载 作者:行者123 更新时间:2023-12-01 04:53:52 24 4
gpt4 key购买 nike

Ajax 数据被视为文字

我正在使用 jQuery UI 自动完成。它与本地数据源一起工作得很好。但是当我将数据源更改为远程ajax数据源时,它不像本地数据源那样工作。似乎它将回调数据视为文字或字符串而不是像数组或 JSON 这样的数据源,即使回调数据是 JSON。另外,回调数据的格式与本地数据相同。

本地数据源:

var local = [
{
"label": "item 1",
"value": "item 1",
"id": 1
},
{
"label": "item 2",
"value": "item 2",
"id": 2
},
{
"label": "item 3",
"value": "item 1",
"id": 3
}
];

打印到控制台的回调数据源:

[
{
"label": "CIS104",
"value": "CIS104",
"id": "35"
},
{
"label": "CIS214",
"value": "CIS214",
"id": "60"
},
{
"label": "CIS256",
"value": "CIS256",
"id": "61"
},
{
"label": "CIS335",
"value": "CIS335",
"id": "62"
}
];

这是我的 HTML:

<head> 
<title>AutoComplete TextBox with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">

var localsource = [
{ "label": "item 1", "value": "item 1", "id": 1 },
{ "label": "item 2", "value": "item 2", "id": 2 },
{ "label": "item 3", "value": "item 1", "id": 3}];

$(function() {
$("[id$=txtAuto]").autocomplete(
{
source: function(request, response) {
$.ajax(
{
url: "/playground/service/PlayGroundWebService.asmx/GetListOfCourse",
data: "{ 'param': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function(data) {
//data.d because it's .NET web application

var remotesource = data.d;
//It works if remotesource = localsource
response(remotesource);
console.log(remotesource);
},
error: function(result) { }
});
},
select: function(event, ui) {
alert(ui.item.id);
}
});
});

</script>
</head>
<body>

<div class="demo">
<div class="ui-widget">
<label for="txtAuto">Enter Course # or title: </label>
<input id="txtAuto" type="text" style="width: 600px" />
</div>
</div>

</body>
</html>

谁能告诉我问题出在哪里吗?谢谢

更新1:

console.log(data) 给出:

Object { d=

"[ { "label": "CIS104", "value": "CIS104", "id": "35" },
{ "label": "CIS214", "value": "CIS214", "id": "60" },
{ "label": "CIS256", "value": "CIS256", "id": "61" },
{ "label": "CIS335", "value": "CIS335", "id": "62" } ]"

}

最佳答案

我明白了。我需要使用 JavaScript eval 方法将远程数据源转换为 JavaScript 对象(字符串 -> 对象)

// Change var remotesource = data.d; to this:

var remotesource = eval("(" + data.d + ")");

关于jquery - Ajax 数据回调被视为文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16459873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com