如果您不想在对$ .ajax()的调用中进行定义,则在哪里定义jQuery $ .ajax()成功函数? [英] Where to define a jQuery $.ajax() success function if you don't want to define in the call to $.ajax()?

查看:60
本文介绍了如果您不想在对$ .ajax()的调用中进行定义,则在哪里定义jQuery $ .ajax()成功函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I want to separate out my ajax success function so that it is defined elsewhere in my <script>, does it have to be inside the

$(document).ready(function()
{

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

section or could it be defined along with non-jQuery javascript functions?

  $.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);
    }
  });

我不想在对ajax的调用中定义它的原因是,它最终将是一个大函数,并且如果将其与其他ajax调用参数混合使用,则会导致读取混乱.

The reason I don't want to define it inside the call to ajax is it will eventually be a large function and it will be confusing to read if it's mixed in with the other ajax call parameters.

例如,是否可以:

$.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);
}

推荐答案

您必须对其进行更改,以便仅使用函数名称.像这样:

You have to change it so its only the function name. Like so:

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

您需要像这样声明它的地方放置put函数

And you need put function where you declare it like so

function handlePrayer(data)
{
    $('#prayer_date').html(data.Date);
    console.log(data);
}

这篇关于如果您不想在对$ .ajax()的调用中进行定义,则在哪里定义jQuery $ .ajax()成功函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆