programing

jquery AJAX 성공 콜백에서 함수에 변수 전달

nasanasas 2020. 11. 16. 21:36
반응형

jquery AJAX 성공 콜백에서 함수에 변수 전달


jQuery AJAX 호출을 사용하여 일부 이미지를 미리로드하려고하지만 AJAX 호출의 성공 함수 내에서 (URL) 문자열을 함수에 전달하는 데 실제 문제가 있습니다 (해당되는 경우).

내 코드는 다음과 같습니다.

//preloader for images on gallery pages
window.onload = function() {
    setTimeout(function() {     
        var urls = ["./img/party/"]; //just one to get started

        for ( var i = 0; i < urls.length; i++ ) {
            $.ajax({
                url: urls[i],
                success: function(data,url) {
                    $(data).find("a:contains(.jpg)").each(function(url) {                               
                        new Image().src = url + $(this).attr("href");
                    });
                }
            });
        };  
    }, 1000);
};

URL을 .each()호출 에 전달하려는 내 (실패한) 시도를 볼 수 있습니다. 결국 url증가하는 정수 값을 가져옵니다. 왜 jpg 파일의 수와 관련이 있는지 잘 모르시겠습니까?

... 어쨌든, 물론 내 원래 URL 배열에서 단일 값을 가져야합니다.

도움을 주셔서 감사합니다. 저는 항상 이러한 콜백으로 약간의 왜곡을 겪는 것 같습니다.


진행?

그래서 저는 @ron tornambe와 @PiSquared의 댓글에주의를 기울여서 조금씩 돌아 다니며 현재 여기에 있습니다.

//preloader for images on gallery pages
window.onload = function() {
    var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];

    setTimeout(function() {
        for ( var i = 0; i < urls.length; i++ ) {
            $.ajax({
                url: urls[i],
                success: function(data) {
                    image_link(data,i);
                    function image_link(data, i) {
                        $(data).find("a:contains(.jpg)").each(function(){ 
                            console.log(i);
                            new Image().src = urls[i] + $(this).attr("href");
                        });
                    }
                }
            });
        };  
    }, 1000);       
};

나는 image_link(data, i)여기 저기 그리고 모든 곳에 (각 중첩 된 함수 등에) 넣을 시도했지만 동일한 결과를 얻었습니다.의 값 i은 3으로 기록됩니다. 모든 참조가 i동일한 것을 가리키고 에 비동기 작업이 실제로 도착 시간 루프가 끝나고 함께 할 (따라서 3의 값을 갖는다). 말할 필요도없이 이것은 '정의되지 않음'으로 제공 됩니다.image_link(data, i)for...urls[i]

이 문제를 해결하는 방법에 대한 (더 많은) 팁이 있습니까?


설정 객체가 해당 ajax 호출에 연결되어 있으므로 인덱서에 사용자 정의 속성을 추가하기 만하면 this성공 콜백에서 사용하여 액세스 할 수 있습니다 .

//preloader for images on gallery pages
window.onload = function() {
    var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];

    setTimeout(function() {
        for ( var i = 0; i < urls.length; i++ ) {
            $.ajax({
                url: urls[i],
                indexValue: i,
                success: function(data) {
                    image_link(data , this.indexValue);

                    function image_link(data, i) {
                        $(data).find("a:contains(.jpg)").each(function(){ 
                            console.log(i);
                            new Image().src = urls[i] + $(this).attr("href");
                        });
                    }
                }
            });
        };  
    }, 1000);       
};

편집 : 업데이트 된 JSFiddle 예제를 추가하면 ECHO 엔드 포인트가 작동하는 방식이 변경된 것으로 보입니다 : https://jsfiddle.net/djujx97n/26/ .

이것이 어떻게 작동하는지 이해하려면 ajaxSettings 객체의 "context"필드를 참조하십시오 : http://api.jquery.com/jquery.ajax/ , 특히 다음 참고 :

" this모든 콜백 내의 참조는 설정에서 $ .ajax에 전달 된 컨텍스트 옵션의 객체입니다. 컨텍스트가 지정되지 않은 경우 이는 Ajax 설정 자체에 대한 참조입니다."


다음과 같이 시도하십시오 (url을 얻으려면 this.url 사용) :

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

여기 에서 찍은


객체를 통해 여러 매개 변수를 전달 하기 위해 indexValue 속성을 사용할 수도 있습니다 .

var someData = "hello";

jQuery.ajax({
    url: "http://maps.google.com/maps/api/js?v=3",
    indexValue: {param1:someData, param2:"Other data 2", param3: "Other data 3"},
    dataType: "script"
}).done(function() {
    console.log(this.indexValue.param1);
    console.log(this.indexValue.param2);
    console.log(this.indexValue.param3);
}); 

You can't pass parameters like this - the success object maps to an anonymous function with one parameter and that's the received data. Create a function outside of the for loop which takes (data, i) as parameters and perform the code there:

function image_link(data, i) {
   $(data).find("a:contains(.jpg)").each(function(){                                
       new Image().src = url[i] + $(this).attr("href");
   }
}
...
success: function(data){
    image_link(data, i)
}

I'm doing it this way:

    function f(data,d){
    console.log(d);
    console.log(data);
}
$.ajax({
    url:u,
    success:function(data){ f(data,d);  }
});

Just to share a similar problem I had in case it might help some one, I was using:

var NextSlidePage = $("bottomcontent" + Slide + ".html");

to make the variable for the load function, But I should have used:

var NextSlidePage = "bottomcontent" + Slide + ".html";

without the $( )

Don't know why but now it works! Thanks, finally i saw what was going wrong from this post!


I've meet the probleme recently. The trouble is coming when the filename lenght is greather than 20 characters. So the bypass is to change your filename length, but the trick is also a good one.

$.ajaxSetup({async: false}); // passage en mode synchrone
$.ajax({
   url: pathpays,
   success: function(data) {
      //debug(data);
      $(data).find("a:contains(.png),a:contains(.jpg)").each(function() {
         var image = $(this).attr("href");
         // will loop through
         debug("Found a file: " + image);
         text +=  '<img class="arrondie" src="' + pathpays + image + '" />';
      });
      text = text + '</div>';
      //debug(text);
   }
});

After more investigation the trouble is coming from ajax request: Put an eye to the html code returned by ajax:

<a href="Paris-Palais-de-la-cite%20-%20Copie.jpg">Paris-Palais-de-la-c..&gt;</a>
</td>
<td align="right">2015-09-05 09:50 </td>
<td align="right">4.3K</td>
<td>&nbsp;</td>
</tr>

As you can see the filename is splitted after the character 20, so the $(data).find("a:contains(.png)) is not able to find the correct extention.

But if you check the value of the href parameter it contents the fullname of the file.

I dont know if I can to ask to ajax to return the full filename in the text area?

Hope to be clear

I've found the right test to gather all files:

$(data).find("[href$='.jpg'],[href$='.png']").each(function() {  
var image = $(this).attr("href");

참고URL : https://stackoverflow.com/questions/18413969/pass-variable-to-function-in-jquery-ajax-success-callback

반응형