programing

jQuery가 비동기 Ajax 요청이 아닌 동기 Ajax 요청을 수행하도록 하려면 어떻게 해야 합니까?

randomtip 2023. 1. 15. 12:59
반응형

jQuery가 비동기 Ajax 요청이 아닌 동기 Ajax 요청을 수행하도록 하려면 어떻게 해야 합니까?

JavaScript를 사용합니다.그 중 하나가beforecreate기능.그것은 돌아올 것이다.false항목이 생성되지 않도록 합니다.

jQuery를 사용하여 이 함수에 Ajax 호출을 추가했습니다.

beforecreate: function (node, targetNode, type, to) {
  jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),

  function (result) {
    if (result.isOk == false) 
        alert(result.message);
  });
}

을 작성하지 싶기 해야 합니다.false 기타 API 요구를 ?jQuery 또는 다른 브라우저 API를 사용하여 동기화된 AJAX 요청을 수행하는 방법이 있습니까?

jQuery 문서에서: 동기 Ajax 요청을 가져오려면 비동기 옵션을 false로 지정합니다.그러면 콜백이 어머니 기능이 진행되기 전에 몇 가지 데이터를 설정할 수 있습니다.

제안된 대로 변경된 코드는 다음과 같습니다.

beforecreate: function (node, targetNode, type, to) {
    jQuery.ajax({
        url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
        success: function (result) {
            if (result.isOk == false) alert(result.message);
        },
        async: false
    });
}

를 호출하여 jQuery의 Ajax 설정을 동기 모드로 설정할 수 있습니다.

jQuery.ajaxSetup({async:false});

Ajax 을 Ajax로 합니다.jQuery.get( ... );

그럼 다시 한 번 켜면 돼

jQuery.ajaxSetup({async:true});

하는 것과 이 될 것만, @Adam을 이 될 수 .jQuery.get() ★★★★★★★★★★★★★★★★★」jQuery.post() 더 공들여 말하면jQuery.ajax()구문을 사용합니다.

뛰어난 솔루션!구현하려고 했을 때 success 절에 값을 반환하면 정의되지 않은 것으로 반환된다는 것을 알게 되었습니다.변수에 저장하고 변수를 반환해야 했습니다.제가 생각해낸 방법은 다음과 같습니다.

function getWhatever() {
  // strUrl is whatever URL you need to call
  var strUrl = "", strReturn = "";

  jQuery.ajax({
    url: strUrl,
    success: function(html) {
      strReturn = html;
    },
    async:false
  });

  return strReturn;
}

이러한 응답은 모두 Ajax 콜을 async:false로 실행하면 Ajax 요구가 완료될 때까지 브라우저가 중단된다는 점을 간과하고 있습니다.흐름 제어 라이브러리를 사용하면 브라우저를 끊지 않고 이 문제를 해결할 수 있습니다.Frame.js의 예를 다음에 나타냅니다.

beforecreate: function(node,targetNode,type,to) {

    Frame(function(next)){

        jQuery.get('http://example.com/catalog/create/', next);
    });

    Frame(function(next, response)){

        alert(response);
        next();
    });

    Frame.init();
}
function getURL(url){
    return $.ajax({
        type: "GET",
        url: url,
        cache: false,
        async: false
    }).responseText;
}


//example use
var msg=getURL("message.php");
alert(msg);

(JSONP를 사용하여) 도메인 간 Ajax 콜을 실행하는 경우 동기화할 수 없습니다.asyncjQuery를 사용하다

$.ajax({
    url: "testserver.php",
    dataType: 'jsonp', // jsonp
    async: false //IGNORED!!
});

JSONP 콜의 경우는, 다음을 사용할 수 있습니다.

  1. Ajax-call to your domain(사용자 자신의 도메인에 대한 콜) - 교차 도메인 콜서버측을 실행합니다.
  2. 비동기적으로 작동하도록 코드 변경
  3. Frame.js와 같은 "함수 시퀀서" 라이브러리를 사용합니다( 답변).
  4. 실행을 차단하는 대신 UI를 차단합니다( 답변). (가장 좋아하는 방법)

의 : 용 : note note note note note note note note note note note 는 사용하지 마십시오async: false하다

Gecko 30.0(Firefox 30.0/Thunderbird 30.0/SeaMonkey 2.27)부터는 사용자 경험에 부정적인 영향을 미치기 때문에 메인 스레드에 대한 동기 요청이 폐지되었습니다.

Chrome은 콘솔에 경고까지 합니다.

메인 스레드의 동기 XMLHttpRequest는 최종 사용자의 경험에 악영향을 미치기 때문에 권장되지 않습니다.상세한 것에 대하여는, https://xhr.spec.whatwg.org/ 를 참조해 주세요.

이러한 작업을 하고 있으면 언제든지 작동이 중지될 수 있으므로 페이지가 끊어질 수 있습니다.

동기화 되어 있으면서도 차단하지 않는 것처럼 느끼고 싶다면 비동기/대기 및 새로운 Fetch API와 같은 약속에 기초한 일부 Ajax를 사용해야 합니다.

async function foo() {
  var res = await fetch(url)
  console.log(res.ok)
  var json = await res.json()
  console.log(json)
}

사용자가 페이지를 이동 중이거나 닫을 때 페이지 삭제 동기화 XHR을 허용하지 않음에 대해 Chrome 편집 작업이 진행 입니다.여기에는 언로드 전, 언로드, 페이지 숨기기 및 가시성 변경이 포함됩니다.

이것이 사용 예라면, Navigator를 참조해 주세요.sendBeacon 대신

또한 페이지에서 http 헤더 또는 iframe의 allow Atribute를 사용하여 sync req를 비활성화할 수도 있습니다.

저는 Carcione의 답변을 사용하여 JSON을 사용하도록 수정했습니다.

 function getUrlJsonSync(url){

    var jqxhr = $.ajax({
        type: "GET",
        url: url,
        dataType: 'json',
        cache: false,
        async: false
    });

    // 'async' has to be 'false' for this to work
    var response = {valid: jqxhr.statusText,  data: jqxhr.responseJSON};

    return response;
}    

function testGetUrlJsonSync()
{
    var reply = getUrlJsonSync("myurl");

    if (reply.valid == 'OK')
    {
        console.dir(reply.data);
    }
    else
    {
        alert('not valid');
    }    
}

'JSON' dataType을 추가하고 .responseText를 responseJ로 변경했습니다.아들

또한 상태를 사용하여 상태를 검색했습니다.반환된 개체의 텍스트 속성입니다.이것은 Ajax 응답 상태이지 JSON의 유효 여부가 아닙니다.

백엔드는 올바른(올바른) JSON으로 응답을 반환해야 합니다.그렇지 않으면 반환된 오브젝트는 정의되지 않습니다.

원래 질문에 대답할 때 고려해야 할 두 가지 측면이 있습니다.하나는 Ajax에게 동기적으로 실행하도록 지시하고(비동기:false를 설정함으로써), 다른 하나는 콜백 함수가 아닌 호출 함수의 리턴 문을 통해 응답을 반환합니다.

POST에서도 시도해 봤는데 잘 되더라고요.

GET을 POST로 변경하고 데이터: postdata를 추가했습니다.

function postUrlJsonSync(url, postdata){

    var jqxhr = $.ajax({
        type: "POST",
        url: url,
        data: postdata,
        dataType: 'json',
        cache: false,
        async: false
    });

    // 'async' has to be 'false' for this to work
    var response = {valid: jqxhr.statusText,  data: jqxhr.responseJSON};

    return response;
}

위의 코드는 비동기 코드가 false인 경우에만 기능합니다.async: true를 설정한 경우 반환된 오브젝트 jqxhr은 AJAX 콜이 반환될 때 활성화되지 않습니다.나중에 비동기 콜이 종료되었을 때에만 유효하지만 응답 변수를 설정하기에는 너무 늦습니다.

와 함께async: false차단된 브라우저를 사용할 수 있습니다.비블로킹 동기 솔루션의 경우 다음을 사용할 수 있습니다.

ES6/ECMAScript2015

ES6에서는 제너레이터와 co 라이브러리를 사용할 수 있습니다.

beforecreate: function (node, targetNode, type, to) {
    co(function*(){  
        let result = yield jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value));
        //Just use the result here
    });
}

ES7

ES7에서는 asyc wait만 사용할 수 있습니다.

beforecreate: function (node, targetNode, type, to) {
    (async function(){
        let result = await jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value));
        //Just use the result here
    })(); 
}

다음은 예를 제시하겠습니다.

$.ajax({
  url: "test.html",
  async: false
}).done(function(data) {
   // Todo something..
}).fail(function(xhr)  {
   // Todo something..
});

먼저 $.ajax를 사용할 때와 $.get/$post를 사용할 때를 이해해야 합니다.

요청 헤더 설정, 캐싱 설정, 동기 설정 등 Ajax 요청에 대한 낮은 수준의 제어가 필요한 경우 $.ajax를 선택해야 합니다.

$.get/$post: ajax 요구에 대한 낮은 수준의 제어가 필요하지 않은 경우.서버에 데이터를 간단하게 취득/포스트 할 수 있습니다.의 줄임말이다

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

따라서 $.get/$post에서는 다른 기능(동기, 캐시 등)을 사용할 수 없습니다.

따라서 ajax 요청에 대한 낮은 수준의 제어(sync, cache 등)를 위해서는 $.ajax를 선택해야 합니다.

 $.ajax({
     type: 'GET',
      url: url,
      data: data,
      success: success,
      dataType: dataType,
      async:false
    });

이것은 jQuery를 사용한 비동기 요청의 간단한 구현입니다.이게 누구에게나 도움이 됐으면 좋겠어요.

var queueUrlsForRemove = [
    'http://dev-myurl.com/image/1', 
    'http://dev-myurl.com/image/2',
    'http://dev-myurl.com/image/3',
];

var queueImagesDelete = function(){

    deleteImage( queueUrlsForRemove.splice(0,1), function(){
        if (queueUrlsForRemove.length > 0) {
            queueImagesDelete();
        }
    });

}

var deleteImage = function(url, callback) {
    $.ajax({
        url: url,
        method: 'DELETE'
    }).done(function(response){
        typeof(callback) == 'function' ? callback(response) : null;
    });
}

queueImagesDelete();

왜냐면XMLHttpReponse동기 조작은 권장되지 않습니다.저는 다음과 같은 해결책을 생각해 냈습니다.XMLHttpRequest이것에 의해, 순서부여된 AJAX 쿼리는, 본래 비대칭인 채로 사용할 수 있게 되어, 1회용 CSRF 토큰에 매우 편리합니다.

또한 투명하므로 jQuery 등의 라이브러리가 원활하게 작동합니다.

/* wrap XMLHttpRequest for synchronous operation */
var XHRQueue = [];
var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function()
{
  var xhr   = new _XMLHttpRequest();
  var _send = xhr.send;

  xhr.send = function()
  {
    /* queue the request, and if it's the first, process it */
    XHRQueue.push([this, arguments]);
    if (XHRQueue.length == 1)
      this.processQueue();
  };

  xhr.processQueue = function()
  {
    var call = XHRQueue[0];
    var xhr  = call[0];
    var args = call[1];

    /* you could also set a CSRF token header here */

    /* send the request */
    _send.apply(xhr, args);
  };

  xhr.addEventListener('load', function(e)
  {
    /* you could also retrieve a CSRF token header here */

    /* remove the completed request and if there is more, trigger the next */
    XHRQueue.shift();
    if (XHRQueue.length)
      this.processQueue();
  });

  return xhr;
};

원래 질문이 뭐였냐면jQuery.get(여기서 설명한 바와 같이) 를 사용할 수 있다는 것을 여기서 언급할 필요가 있습니다.async: false에 있어서$.get()이상적으로는 비동기식이기 때문에 피해야 합니다.XMLHTTPRequest는 권장되지 않습니다(브라우저에서 경고가 표시될 수 있습니다).

$.get({
  url: url,// mandatory
  data: data,
  success: success,
  dataType: dataType,
  async:false // to make it synchronous
});

언급URL : https://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re

반응형