如何获取提供给ajax回调中ajax调用的原始数据?

时间:2019-05-05 01:07:09

标签: javascript jquery

基本上,我正在遍历图像数组。如果图像没有源,它将进行ajax调用来查找对象的图像并将URL设置为image元素的src来调用图片。但是,调用“ this”将引用ajax调用而不是image元素。我现在的方法是从“选项”中的“数据”中获取元素的元素ID,但这是行不通的。我还尝试从成功回调内部调用“ imageOf”,但这也不起作用。

$("img").each(function() {
        if (!$(this).attr("src")) {
            var imageOf = $(this).attr("imageOf");

            //get imageURL via ajax call
            var pixabayAPI = "https://pixabay.com/api/";

            $.ajax(pixabayAPI, {
                method: "GET",
                async: false,
                dataType: "json",
                data: {
                    key: "...",
                    q: imageOf,
                    category: "food"
                },
                success: function(result, status, jqXHR) {
                    var images = result.hits;
                    if (images.length > 0){
                        console.log(images[0].webformatURL);
                        $(this).attr("src", images[0].webformatURL);

                        // "this" becomes the ajax call when I want to get the image element instead
                    };
                },
                error: function(e) {
                    console.log(e);
                }
            });
        }
    });

1 个答案:

答案 0 :(得分:-3)

GET请求没有数据-基本上是请求的主体。 因此,对于此解决方案,最好的做法是在URL内提供API密钥,如下所示:

https://pixabay.com/api/?key= $ {key}&q = $ {imageOf}&image_type = photo

不要强制将此搅动放入反引号(`)中,因为它是使用变量 key imageOf

插入的字符串

然后,您可以像他们的API文档中所述:https://pixabay.com/api/docs/