【问题标题】:problem with jQuery Tokeninput and asp.net webservicejQuery Tokeninput 和 asp.net webservice 的问题
【发布时间】:2011-08-01 14:57:38
【问题描述】:

我在我的网站中编写了以下 webservice asmx 文件:

[WebService(Namespace = "http://eumcore.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class jsonTest : System.Web.Services.WebService {

    public jsonTest () {

    }

    [WebMethod(Description = "Gets the names matching part of a title.")]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void getName() {
        List<nameEntry> nameList = new List<nameEntry>();
        nameList.Add(new nameEntry() {id="1", name="John"});
        nameList.Add(new nameEntry() { id = "3", name = "Alex" });
        this.Context.Response.ContentType = "application/json; charset=utf-8";

        JavaScriptSerializer js = new JavaScriptSerializer();
        string strJSON = js.Serialize(nameList);
        this.Context.Response.Write(strJSON);
    }    
}

一开始我希望它每次都返回相同的数组,当我直接调用它时,webservice的结果是:

[{"id":"1","name":"John"},{"id":"3","name":"Alex"}]

哪个是正确的回复,当我将它用作本地输入时,结果很好,但是当我在 tokeninput 的输入法中调用 web 服务时(我为函数分配了一条错误消息),我收到以下错误:“ 200 解析器错误未定义”

谁能帮我弄清楚?

谢谢

多伦

编辑:在玩弄了一下 jquery 代码后,我设法接收到数据,但出现以下错误:

200

解析器错误

[{"id":"1","name":"aaA"},{"id":"3","name":"aaA"}]{"d":null}

我不明白的是 d 是什么,为什么它是 null?

【问题讨论】:

  • when i call the webservice in the input method of tokeninput 是什么意思?
  • 从运行 jquery 的 html 中:
  • 您尝试从中调用此 Web 服务的网页是否也托管在 localhost:61965 上,还是位于单独的应用程序中?
  • 它不是应用程序的一部分,但文件本身在机器上。它到达目的地是因为我的代码中有断点并且它停止了
  • 您似乎正在尝试执行不允许的跨域 AJAX 请求。同源策略规定您必须仅将 AJAX 请求发送到同一个域。确保这一点的最佳方法是永远不要使用绝对网址,而只使用相对网址,例如:$("#demo-input").tokenInput("/names/jsonTest.asmx/getName");

标签: jquery asp.net json jquery-plugins


【解决方案1】:

shouldn't be manually serializing that JSON 并写出来。如果您允许,ASP.NET 会自动为您执行此操作:

[WebMethod(Description = "Gets the names matching part of a title.")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<nameEntry> getNames() {
    List<nameEntry> nameList = new List<nameEntry>();

    nameList.Add(new nameEntry() {id="1", name="John"});
    nameList.Add(new nameEntry() { id = "3", name = "Alex" });

    return nameList;
}

要注意的是,you need to call the service a particular way with jQuery 是为了获得 JSON 响应而不是 XML,特别是使用内容类型为 application/json 的 POST 请求。

【讨论】:

  • 由于某种原因,这是以 xml 格式输出数据,尽管它以响应格式显示 json
  • 您需要确保使用内容类型设置为application/json 的POST 发出请求。如果此插件不允许您直接指定,您始终可以在插件运行之前使用 $.ajaxSetup() 全局设置这些选项。
【解决方案2】:

asp.net 不将返回数据包装在一个对象中以确保安全吗?例如,您并没有取回您认为的数组,而是一个在 ["d"] 属性下包含您的数组的对象 {}。

我认为插件需要一个对象数组,因此您可能无法将 url 传递给 tokeninput 初始化程序。相反,在 JSON 请求的回调中将数据取出并放入正确的形式(对象数组),然后使用该数组初始化 tokeninput 插件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 2010-10-17
    相关资源
    最近更新 更多