如果您不想在$ .ajax()的调用中定义jQuery $ .ajax()成功函数,请在何处定义?

Ken*_*ume 1 jquery

如果我想分离出我的ajax success函数,以便它在我的其他地方定义<script>,它是否必须在我的内部

$(document).ready(function()
{
Run Code Online (Sandbox Code Playgroud)

部分还是可以与非jQuery javascript函数一起定义?

  $.ajax(
  {
    url: '/load_prayer',
    cache: false,
    dataType: 'json',
    type: 'POST',
    data: ({ 'prayerId' : prayerId }),
    success: function(data)
    {
        $('#prayer_date').html(data.Date);
        console.log(data);
    },
    error: function(e, xhr)
    {
        console.log(e);
    }
  });
Run Code Online (Sandbox Code Playgroud)

我不想在调用中定义它的原因ajax是它最终将是一个大函数,如果它与其他ajax调用参数混合在一起会令人困惑.

例如,这会工作:

$.ajax(
{
    url: '/load_prayer',
    cache: false,
    dataType: 'json',
    type: 'POST',
    data: ({ 'prayerId' : prayerId }),
    success: handlePrayer(data),
    error: function(e, xhr)
    {
        console.log(e);
    }
});

handlePrayer(data)
{
    $('#prayer_date').html(data.Date);
    console.log(data);
}
Run Code Online (Sandbox Code Playgroud)

Ami*_*far 10

您必须更改它,因此它只是功能名称.像这样:

$.ajax(
{
    url: '/load_prayer',
    cache: false,
    dataType: 'json',
    type: 'POST',
    data: ({ 'prayerId' : prayerId }),
    success: handlePrayer,
    error: function(e, xhr)
    {
        console.log(e);
    }
});
Run Code Online (Sandbox Code Playgroud)

你需要把函数放在你声明它的地方

function handlePrayer(data)
{
    $('#prayer_date').html(data.Date);
    console.log(data);
}
Run Code Online (Sandbox Code Playgroud)