0

我只想使用函数外部的变量,但我不确定我必须为此做什么......

行是否var myRequest = a;足以在函数中使用此变量?

因为我看到了这样一个例子:var myRequest = e.which;

我问这个是因为我的请求没有得到成功的结果。

我认为它没有像我预期的那样工作,因为ajaxFunction(3)工作与写入send.php?goto=3浏览器的地址栏不同。

您可以看到以下代码:

function ajaxFunction(a)
{
    var ajaxRequest;
    try {
        ajaxRequest = new XMLHttpRequest();
    } catch (e) {
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("Your browser broke!");
                return false;
            }
        }
    }
    ajaxRequest.open("GET", "send.php?goto=" + a, true);
    ajaxRequest.send(); 
}
4

3 回答 3

1

如果要在函数外部使用变量,则必须使用全局范围变量,例如(使用 jQuery ajax)

var globalA = null;

$(document).ready(function(){
    var localA1 = null;
    $.ajax({
       "url":"http://someurl.com/",
       "type":"POST",
       "dataType":"json",
       "success":function(incomingData){
           var localA2 = incomingData //localA2 only useable inside this function
           localA1 = incomingData; //localA1 being set here still can only be used here as code within the "ready" function has already been executed and will see it as null
           globalA = incomingData; //Now any further code should use globalA as it now contains useable data
           doSomethingWithData();
       },
       "error":function(xhr,msg) {
           alert("Ajax Error:"+msg);
       }
    });
    alert(localA1); //Will give alertbox with null in it as localA1 has not been set.
});

function doSometingWithData() {
    alert(globalA); //You can now use the data in whatever function makes reference to globalA
}

当然,在这个例子中,您可以直接将数据传递到doSomethingWithData()那里并在那里进行处理。

于 2012-10-31T20:42:34.633 回答
0

您可以查看$.globalEval用于在 AJAX 成功函数中全局实例化变量的 jQuery。

$.ajax({
  url: "send.php",
  success: function (data) {
    $.getScript("somescript.js", function(data) {
      $.globalEval("var something = new Whatever;");
    });
}); 

如果您发现需要在 ajax 调用中加载外部 JS 文件并使其资产全局可用,则 $.getScript 部分是一个有用的小片段。然后,您可以使用$.globalEval在 AJAX 函数中实例化一个变量。

$.globalEval 的文档

jQuery AJAX 文档

于 2012-10-31T21:15:12.037 回答
-2

You don't a function wrapper for setting a value to a variable.

var myRequest = a;

That is good enough.

After thought revision

in a very basic way a variable can be created on its own like a place holder.

var myRequest;

when you get to the function (say you have a series of functions.

You could do something like this.

function(myRequest=a);

if the function has more than one argument it can look like this.

function(myRequest=a,myConcern=b); as you have it stated in the

var arg1 = 1;
var arg2 = 2;
var arg3 = 3;

ajaxRequest.open(arg1,arg2,arg3);

I hope this is helpful and yes, some more info would help (like the poster below stated).

于 2012-10-31T20:25:34.183 回答