Answer the question
In order to leave comments, you need to log in
In Ajax, how can I make the server's response available to the whole script, not just the special Ajax area?
$(document).ready(function(){
$.ajax({
url: 'ajax.php',
type: 'POST',
data: 't1f=0&t1t=6',
dataType: 'json',
success: function(resp){
alert(resp[0].id); //Тут работает.
}})});
alert(resp[0].id);//Тут уже нет.
Answer the question
In order to leave comments, you need to log in
ThunderCat correctly showed
you how to put a variable in the outer scope . But the alert will still "show a fig" because it will be executed BEFORE the ajax request is fired. Although this request is written above, it is not executed instantly. And if the request is successfully completed, then the answer will get into the variable, of course, but already AFTER the alert is triggered. If, instead of an alert, the same information is output by a button, or with a delay by setTimeout, for example, then the data from the response will already be visible.
Read about async in js , use async/await or callback functions.
var someGlobal;
$(document).ready(function(){
$.ajax({...
success: function(resp){
someGlobal = resp;
...
}})});
alert(someGlobal); //Тут все равно фига :)
It should be borne in mind that the Ajax request is asynchronous, that is, the alert immediately after the Ajax code will give you a fig with butter, since this code will be executed at the moment the request is initialized, and not after receiving the response. special area AjaxIs that how you understand the scope of variables? It's funny))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question