我在这篇文章中尝试了解决方案 - using ajax beforeSend to modify data - 但传递的参数不包含isAjax键。
给出的解决方案:
$.ajaxSetup({
data:{
isAjax:true
}
});
这是我的咖啡因:
$.fn.related_table = (table,focus)->
$(this).submit ->
$.ajaxSetup data:
isAjax: true
fs = $(this).serializeArray()
row = build_output fs
$("#{table} > tbody:last").append(row)
$(table).toggle(true)
$.ajax(
data: fs
type: "POST"
cache: false
dataType: "json"
success : (res, status, xhr) => [
$("#{table} tr.pending").addClass("success"),
anim_success("#{table} > tbody > tr.pending > td.saved:last-of-type"),
$(this)[0].reset() ]
error : (xhr, status, err) => [
$("#{table} tr:last-of-type").addClass("error"),
anim_error("#{table} > tbody > tr.pending > td.saved:last-of-type") ]
complete : (xhr, status) => [
$("#{table} tr.pending").removeClass("pending"),
$("#spinning_wheel").hide(),
$("*[autofocus]:first").focus()]
)
false
你可以看到我在提交处理程序中添加了ajaxSetup,以便尝试确保它不是上下文问题,但我也在其他地方尝试过。该功能在没有修改(甚至使用它)的情况下工作正常,因为它提交数据,它只是不添加或发送额外的参数。
我对javascript / coffeescript / jquery不太熟悉,所以我非常感谢有关如何实现这一目标的任何见解。
JQuery版本是1.8.16。
我尝试了几种不同的方法让它工作,但无法做到。我已经在github上设置了一个repo,其中有一个简单的网站来测试这个,如果有人想要使用它https://github.com/yb66/Stackoverflow-question-9337273。
幸运的是,我发现西纳特拉有一个辅助方法request.xhr?
,我可以使用,而不是我试图做的,但我仍然可以看到这将是有益的,所以我会离开的问题开放。
答案 0 :(得分:1)
我没有看到你在$ .ajax调用中设置url
,否则看起来没问题。
这可以按预期工作,请参阅此jsFiddle:
如果您更改以下行:
json: '{"my": "cat"}'
以其他方式,例如:
jsonXXX: '{"my": "cat"}'
您将看到顶部的ajaxSetup中的那个,即:
json: '{"hello": "world"}'
按预期获得。
在本地尝试此示例,如果有效,请先将此工作示例转换为CoffeeScript,然后继续构建它。
希望这有帮助。