【问题标题】:jquery post pass multiple arguments to the function?jquery post将多个参数传递给函数?
【发布时间】:2014-12-19 16:21:31
【问题描述】:

这可能是一个愚蠢的问题,但是当我做 jquery post 时,我想不出一种方法来将多个参数传递给函数。

我有这样的事情

$.post("<?php echo site_url("scores")/getScore/?>/", showScore);

我有一个 php 函数 getScore,它回显 json_encode 数据并将其传递给 javascript 函数 showScore。

理想情况下,我想做的是这样的:

var argument1 = 100;

$.post("<?php echo site_url("scores")/getScore/?>/", showScore(json_encoded_data_from_getScore, argument1));

【问题讨论】:

    标签: javascript jquery arguments


    【解决方案1】:

    在您的情况下没有必要使用参数。 在上面的示例中,变量argument1 将在showScore(json_encoded_data_from_getScore) 内部可见,因为它将对该函数关闭。 如果你需要参数,你应该像这样包装你的函数调用 smth

    var argument1 = 100;
    var argument1 = 'foo bar';
    
    $.post("<?php echo site_url("scores")/getScore/?>/", 
        function(theArgument1, theArgument2) {
             // (2) arguments are in closure
             return function(data) { // (3) this functions will be returned from self-called function 
                                     // and then called with parameter 'data' as success handler 
                 showScore.call(this, data, theArgument1, theArgument2); // (4) it's time to invoke 
                                                                         // showScore with
                                                                         // required parameters 
             }
        }(argument1, argument2) // (1) this function calls itself to create closure
    );
    

    【讨论】:

    • 感谢您的快速回复!函数 showScore 实际上与变量不在同一个闭包中,但您的代码示例似乎有效!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-01-27
    • 2016-04-02
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 2020-05-01
    相关资源
    最近更新 更多