由于某种原因,下面的脚本无法运行。
这是我用来生成 json 数据的代码:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Clear()
Response.Write(generate_json_data())
Response.End()
End Sub
这会在屏幕上产生以下输出:
[ {id:0,value:"c++"}, {id:1,value:"java"}, {id:2,value:"php"}, {id:3,value:"coldfusion"}, {id:4,value:"javascript"}, {id:5,value:"asp"}, {id:6,value:"ruby"} ];
这是我到目前为止的jquery,它似乎不起作用。当我在输入字段中输入内容时,它不会给出错误,而当它应该显示 json 数据中的一些数据时,没有任何反应。
$("input").autocomplete({
source: "serverside_array.aspx",
dataType: "json",
select: function (event, ui) {
$("#txtAllowSearch").val(ui.item.value); // display the selected text
$("#txtAllowSearchID").val(ui.item.id); // save selected id to hidden input
}
});
编辑 1:Chromium 10 中开发人员工具的 header
Request URL:http://intranet/test_array.aspx?term=j
Request Method:GET
Status Code:200 OK
Request Headers
Accept:application/json, text/javascript, */*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Type:application/x-www-form-urlencoded
Host:intranet
Referer:http://intranet/rights_stage_three.aspx
User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.17 (KHTML, like Gecko) Chrome/10.0.652.0 Safari/534.17
X-Requested-With:XMLHttpRequest
Query String Parameters
term:j
Response Headers
Cache-Control:private
Content-Length:204
Content-Type:application/json; charset=utf-8
Date:Thu, 27 Jan 2011 16:11:14 GMT
Server:Microsoft-IIS/6.0
X-AspNet-Version:2.0.50727
X-Powered-By:ASP.NET
编辑2:查看响应数据XHR,我得到以下内容
name test_array.aspx
method get
status 200 ok
type application/json
size 204b
time pending
编辑3:
现在我完全困惑了。我通过简单地将 aspx 页面生成的内容类型更改为:
text/xml
而不是
applicaiton/json
为什么当我返回 json 时它可以与 text/xml 一起使用?
最佳答案
使用 Webdev 工具,例如 Firebug 或 Operas 和 Chrome 内置开发工具,它可以列出 HTTP 请求和响应。
检查是否记录了 JavaScript 错误。
如果不是,请检查响应,如果是回调,则响应的 Content-Type 是否为 text/javascript
;如果只是 JSON 数据,则为 application/json
。
如果没有内容类型,由于针对 XSS 的安全性,ajax 请求可能会失败。
关于asp.net - 服务器端 json 的自动完成问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4818019/