简体   繁体   English

访问传递给$ .get的参数进入成功回调函数

[英]Accessing parameters passed to $.get into success callback function

I want to access parameters passed as a data to $.get in jQuery. 我想访问作为数据传递给jQuery中$ .get的参数。 The code is something like this: 代码是这样的:

$.get(requestUrl,
         {lesson: eventParams.lessonId,
          page: eventParams.page}, 
          function(data) {
                // here I want to access 
                // lesson or page 
          });

Now I made something like this: 现在我做了这样的事情:

$.get(requestUrl,
         {lesson: eventParams.lessonId,
          page: eventParams.page}, 
          (function(contextObject) {
                return function(data) {
                // Here I accessing  
                // contextObject.lesson
                // and 
                // contextObject.page               
           }})({lesson: eventParams.lessonId,
                               page: eventParams.page});

This working but will be good if a can avoid using of closure. 这可以工作,但是如果可以避免使用闭包,那将是很好的。 I would appreciate any help. 我将不胜感激任何帮助。 Best regards. 最好的祝福。

Did you declare eventParams ? 您是否声明了eventParams?

var eventParams = '';

You can use var at global scope (outside of all functions) to declare a global variable: 您可以在全局范围内(在所有函数之外)使用var声明全局变量:

var yourGlobalVariable;
function boo() {
    // ...
}

Alternately, you can assign to a property on window: 或者,您可以分配给窗口上的属性:

function foo() {
    window.yourGlobalVariable = ...;
}

Your params object (or at least its properties) is accessible as the this context of your callback, see the docs for the context option : 您的params对象(或至少它的属性)可以作为回调的this上下文访问,请参见docs的context选项

By default, the context is an object that represents the ajax settings used in the call ( $.ajaxSettings merged with the settings passed to $.ajax ) 默认情况下,上下文是一个对象,代表调用中使用的ajax设置( $.ajaxSettings与传递给$.ajax的设置合并)

So use 所以用

$.get(requestUrl, {
    lesson: eventParams.lessonId,
    page: eventParams.page
}, function(data) {
    console.log(this);
    // use this.data.lesson or .page
});

Btw, the closure you're currently using is quite unhelpful because you have too repeat everything. 顺便说一句,您当前正在使用的闭包是完全没有帮助的,因为您已经重复了很多事情。 It would've been easier if you just accessed eventParams from the callback. 如果您只是从回调访问eventParams ,那会更容易。 If you don't trust the context or want to use a closure for clearness, here's how to do it properly (assuming you cannot use eventParams because they're volatile): 如果您不信任context或想要使用闭包来使内容eventParams ,请按以下说明正确执行操作(假设您不能使用eventParams因为它们易失):

(function() {
    var data = {
        lesson: eventParams.lessonId,
        page: eventParams.page
    };
    return $.get(requestUrl, data, function(resultData) {
        // here use data.lesson or .page 
    });
})()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM