【问题标题】:Unexpected token < in JSON at position 2 jquery Autocomplete意外的令牌 < 在 JSON 中的位置 2 jquery 自动完成
【发布时间】:2016-09-13 03:44:41
【问题描述】:

我有一个带有 jQ​​uery“自动完成”的 AJAX 请求,如下面的代码:

    var clientesList = [];

    $("#clientes").autocomplete({
        source: function (request, callback) {
            $.ajax({
                type: "POST",
                url: "../../../Cliente/GetClientesByName",
                data: "{'nome':'" + request.term + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    debugger;
                    callback($.map(data.cities, function (obj) {
                        return obj.Main
                    }))
                }
            })
        }
    })

触发事件时,jquery.min中显示错误??

"Create:2 Uncaught SyntaxError: Unexpected token

我的输入 HTML 是这样的:

<input type="text" id="clientes" class="form-control col-md-10" />

【问题讨论】:

  • 您的远程服务可能返回 HTML 而不是 JSON。此外,您的 data 不是有效的 JSON。试试data: JSON.stringify({nome: request.term})。两者可能相关(错误数据 -> HTML 错误响应)
  • 扩展@Phil 的评论,只有引号是 JSON 中的有效字符串分隔符,而不是撇号。 JSON 可能看起来像 Javascript,但实际上不是。
  • 我打赌您的请求被重定向是因为您已注销、错误处理程序已启动或 404,而 &lt; 来自您实际上正在提供 HTML 文档。

标签: jquery ajax jquery-ui-autocomplete


【解决方案1】:

我的猜测是,由于您的 JSON data 属性格式错误,您的服务器端资源正在返回 HTML 错误,因此响应中出现了意外的 &lt; 字符。

通过创建有效的 JSON 字符串来修复您的数据...

data: JSON.stringify({nome: request.term}),

这将产生一个类似的值

{"nome":"whatever you typed"}

这是有效的,而不是

{'nome':'whatever you typed'}

这不是由于单引号引起的,而且可能更糟,具体取决于request.term 的值。

【讨论】:

    【解决方案2】:

    尝试对响应数据进行字符串化,再解析一下,看看:

    (...)
    success: function (data) {
        // ----------------------------------------------
        // My suggestion
        // ----------------------------------------------
        // Re-rendering the JSON -> Stringify > Parse
        data = jQuery.parseJSON(JSON.stringify(data));
        // Debugging the JSON object in console
        console.log(data); 
        // ----------------------------------------------
    
        debugger;
        callback($.map(data.cities, function (obj) {
            return obj.Main
        }))
    }
    (...)
    

    您可以在相关问题中查看更多信息,例如:Parsing JSON giving "unexpected token o" error

    【讨论】:

      【解决方案3】:

      有效的 json 字符串必须有双引号。

      JSON.parse({"u1":1000,"u2":1100})       // will be ok
      

      没有引号导致错误

      JSON.parse({u1:1000,u2:1100})    
      // error Uncaught SyntaxError: Unexpected token u in JSON at position 2
      

      单引号导致错误

      JSON.parse({'u1':1000,'u2':1100})    
      // error Uncaught SyntaxError: Unexpected token u in JSON at position 2
      

      您必须在 https://jsonformatter.curiousconcept.com/ 处提供有效的 json 字符串

      【讨论】:

        猜你喜欢
        • 2014-07-25
        • 1970-01-01
        • 2019-05-06
        • 2016-12-13
        • 1970-01-01
        • 2017-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多