JavaScript对象构造和赋值不起作用

Wen*_*enn 0 javascript ajax jquery object

有人可以告诉我为什么我的对象img不接受它在ajax调用之外的值吗?我还使用了构造函数来创建对象,但是这个函数也没有用.并且xml解析的值有效,我已经测试过了.如果我在成功事件中移动警报(img.location),将显示正确的值,但它不会在ajax函数之外.

请帮忙...

function getImage(){
        img = new Object();
        $.ajax({
            type: "GET",
            url: "hvimage.xml",
            dataType: "xml",
            success: function(xmlData){
                var randImageId = Math.floor(Math.random()*3);
                $(xmlData).find("image").each(function(index, e){
                    if(index == randImageId){
                        img.id =  $(this).attr("id");
                        img.location = $(this).find("location").text();
                        img.answer = $(this).find("answer").text();
                    }
                });
            },
            error: function(xmdData){
                alert("error");
            }
        });
        alert("test");
        alert(img.location); //Keep getting undefined here..
    }
Run Code Online (Sandbox Code Playgroud)

再次感谢,

德恩

use*_*716 6

因为您的AJAX请求是异步的,所以它之后的代码不会在运行之前等待响应.

任何依赖于成功响应的代码都需要放入success:回调中或从回调中调用.

function getImage(){
    img = new Object();  // 1. create object

      // 2. send request
    $.ajax({
        type: "GET",
        url: "hvimage.xml",
        dataType: "xml",
        success: function(xmlData){

                // 4. response is received, and callback runs
            var randImageId = Math.floor(Math.random()*3);
            $(xmlData).find("image").each(function(index, e){
                if(index == randImageId){
                    img.id =  $(this).attr("id");
                    img.location = $(this).find("location").text();
                    img.answer = $(this).find("answer").text();
                }
            });
        },
        error: function(xmdData){
            alert("error");
        }
    });

      // 3. fire alerts
    alert("test");
    alert(img.location); //Keep getting undefined here..
}
Run Code Online (Sandbox Code Playgroud)