未触发 AJAX 回调的 JSON 返回
Posted
技术标签:
【中文标题】未触发 AJAX 回调的 JSON 返回【英文标题】:JSON return from AJAX callback not fired 【发布时间】:2020-06-24 22:06:45 【问题描述】:我的 AJAX 函数(在 coffeescript 中)正在返回值,但 error
和 success
回调均未触发。
$ ->
$('#sf_field').autocomplete
source: (request, response) ->
$.ajax
url: 'https://XXXXX.my.salesforce.com/services/data/v48.0/search/suggestions'
type: 'GET'
contentType: 'application/json'
cache: false,
crossDomain: true
dataType: 'json'
beforeSend: (xhr) ->
xhr.setRequestHeader 'Authorization', 'Bearer XXXX.XXXXX'
return
data:
q: request.term,
sobject: 'Contact'
success: (data) ->
console.log "success"
alert "success"
json = $.parseJSON(data)
error: () ->
console.log "error"
alert "error"
complete: () ->
console.log "complete"
alert "complete"
select: (event, ui) ->
$("#sf_id").val(ui.item.id)
return
我在 firefox 控制台中看到,XHR 结果是正确的 JSON 格式(在 jsonlint 上验证),但回调似乎没有被触发,我在 UI 中看不到建议(甚至没有日志消息控制台确实出现了)。
浏览器 XHR 响应窗口生成的 JSON:
"autoSuggestResults":["attributes":"type":"Contact",
"url":"/services/data/v48.0/sobjects/Contact/XXXXAU",
"Id":"XXXXXX01uQoVQAU",
"Name":"Martin Aaaaaa",
"attributes":"type":"Contact",
"url":"/services/data/v48.0/sobjects/Contact/XXXXuQoZQAU",
"Id":"XXXXXZQAU",
"Name":"Martin Bbbbbb",
"attributes":"type":"Contact",
"url":"/services/data/v48.0/sobjects/Contact/XXXXojQAE",
"Id":"XXXXXojQAE",
"Name":"Martin Cccccc",
"attributes":"type":"Contact",
"url":"/services/data/v48.0/sobjects/Contact/XXXXQn5QAE",
"Id":"XXXXXQn5QAE",
"Name":"Thomas Martin Dddddd",
"attributes":"type":"Contact",
"url":"/services/data/v48.0/sobjects/Contact/XXXXQv7QAE",
"Id":"XXXXX0001uQv7QAE",
"Name":"Martin Eeeeee"],
"hasMoreResults":true,
"meta":"nameFields":["entityApiName":"Contact",
"fieldApiName":"Name"],
"secondaryFields":[]
我尝试过各种数据类型:(jsonp、text、html),但这无济于事 感谢您的提示
【问题讨论】:
success
和其他回调应该在$ajax
下缩进
我一辈子都无法理解为什么人们在 ES6 上使用 coffeescript。
【参考方案1】:
正如 PGill 所建议的那样,意图是问题所在。 因此,我的咖啡脚本应该如下所示:
$ ->
$('#sf_field').autocomplete
source: (request, response) ->
$.ajax
url: 'https://XXXXX.my.salesforce.com/services/data/v48.0/search/suggestions'
type: 'GET'
contentType: 'application/json'
cache: false,
crossDomain: true
dataType: 'json'
beforeSend: (xhr) ->
xhr.setRequestHeader 'Authorization', 'Bearer XXXX.XXXXX'
return
data:
q: request.term,
sobject: 'Contact'
success: (data) ->
console.log "success"
alert "success"
json = $.parseJSON(data)
error: () ->
console.log "error"
alert "error"
complete: () ->
console.log "complete"
alert "complete"
select: (event, ui) ->
$("#sf_id").val(ui.item.id)
return
【讨论】:
以上是关于未触发 AJAX 回调的 JSON 返回的主要内容,如果未能解决你的问题,请参考以下文章