[英]jQuery $.post returned data
我在如何使用jQuery的$ .post函數返回的數據方面遇到一些問題。 我正在嘗試測試服務器上是否存在圖片。
這是javascript:
$.post("ajax_test_file.php",
{filename: filetocheck},
function(data){
if(data==1){
var img_ref_up = 'value 1';
}else{
var img_ref_up = 'value 1';
}
}
);
[Following code trying to use img_ref_up's value]
這是ajax_test_file.php內容:
$filename = $_POST["filename"];
if (file_exists($filename)) {
echo 1;
} else {
echo 0;
}
我想要做的是在$ .post(...)之后使用img_ref_up的值
有人對此有任何線索嗎? 提前致謝
$.post
正在異步運行,因此您似乎在ajax請求完成之前正在訪問該值。 您可以將代碼移動到成功回調中,這可以確保在使用該變量之前設置image_ref_up
的值。
$.post("ajax_test_file.php",
{filename: filetocheck},
function(data){
if(data==1){
var img_ref_up = 'value 1';
}else{
var img_ref_up = 'value 1';
}
// move your code here
}
);
您不能/不應該-ajax調用是異步的(可以使其同步,但強烈建議不要這樣做)。 您必須在回調方法中處理結果:
$.post("ajax_test_file.php",
{filename: filetocheck},
function(data){
if(data==1){
var img_ref_up = 'value 1';
}else{
var img_ref_up = 'value 1';
}
///// DO WHATEVER YOU NEED HERE
[Following code trying to use img_ref_up's value]
}
);
由於請求是異步的,因此可能會在帖子完成之前執行[以下代碼]部分。 你應該這樣做。
$.post('url', function(data) {
var img_ref_up;
if (data == 1) {
img_ref_up = 'value 1';
}
doSomethingWithRefUp(img_ref_up);
});
function doSomethingWithRefUp(img_ref_up) {
[Following code]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.