English 中文(简体)
如何将变量与 jquery ajax 请求捆绑起来?
原标题:How to bind variable to jquery ajax request?

这不言自明:

while (...) {
    var string= something that changes for each ajax request. ;
    $.ajax({ type :  GET , dataType :  json ,  url :  get_data.php }).done(processData);
}
function processData(data) {
    // get string into here somehow.
}

您可以看到, 我需要将 < code> string 变成 < code> processData 。 我无法做出一个全局变量, 因为 < code> string 在每个 ajax 请求中都不同 。 因此, 问题是, 我如何将 < code> string 绑到我的 ajax 请求中, 这样我才能从 < code> processData 访问它?

我真的不想在查询中附加 string 并让服务器返回它, 但如果这是我唯一的选择, 我别无选择 。

提前感谢。

最佳回答

尝试这样:

while (...) {

    var str =  something that changes for each ajax request. ;

    (function(_str) {
        $.ajax({ type :  GET , dataType :  json ,  url :  get_data.php })
         .done(function(data) {
            processData(data, _str);
         });
    }(str));
}

function processData(data, str) {
  console.log(data, str);
}

并且没有使用全球变量 :)

问题回答
var string= something that changes for each ajax request. ;
// Use a closure to make sure the string value is the right one.
(function() {
    // Store the "string" context
    var that = this;
    $.ajax({
         type :  GET ,
         dataType :  json ,
         url :  get_data.php 
    }).done(
        $.proxy( processData, that )
    );
}(string));

function processData( data ) {
    this.string ===  something that changes for each ajax request.  // true
}

$.proxy 是.bind( 。

@Joel(在他的删除的回答中)建议添加一个参数,但

$(document).bind("ajaxSend",function(){
    $("#ajax_preloader").show();
}).bind("ajaxComplete",function(){
    $("#ajax_preloader").hide();
});




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签