2017-07-10 33 views
-1

拉JSON,我試圖拉我使用這個PHP代碼創建了一個JSON:

if ($result=mysqli_query($conn,$sql)) 
{ 
    $rowcount=mysqli_num_rows($result); 
} 

$myJSON = json_encode($rowcount); 

echo $myJSON; 

我想價值$ myJSON添加到JavaScript變量。目前,我的代碼如下所示:

var maxqty; 
$.getJSON('[URL in here or .php file]', data, function(jsonData) { 
maxqty = jsonData; 
}); 

我知道這應該是一個非常簡單的事,但我不明白的地方我的代碼是怎麼了。我想我的PHP文件不是輸出正確的格式,或者我的$.getJSON調用是錯誤的。我收到一個錯誤,當我讓我的$ .getJSON調用說

Uncaught reference error: data is not defined.

任何意見?

+0

你使用'maxqty'回調函數之外? –

+0

我什麼如果'$ result = mysqli_query($ conn,$ sql)'計算結果爲'false',預期的結果是什麼?使用'.then()'鏈接到'$ .getJSON()'來獲取jQuery promise對象的值,幷包含錯誤處理。 '.getJSON()'異步返回結果。請參閱[如何從異步調用返回響應?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323?s = 1 | 0.8364#14220323) – guest271314

+0

@ SverriM.Olsen是的,我稍後在同一個腳本中將它用於if語句中。 – taurus

回答

1

從服務器加載東西需要時間。從回調中設置外部變量將無法按照您的預期工作。

// The request start here 
var request = $.getJSON('[URL in here or .php file]', data); 

var maxqty = undefined; 

request.done(function (data) { 
    // This callback is called when the data is done 
    // loading. The "data" variable is only available 
    // here, and not outside the callback 

    maxqty = data; 
}); 

// "maxqty" is "undefined" here until the request 
// is done loading 
console.log(maxqty); 
+0

我覺得雖然這不是OP的當前問題,它將是他們的下一個;) – Phil

+0

在這裏進一步閱讀材料〜https://stackoverflow.com/questions/14220321/how-do- i-return-The-asynchronous-call- – Phil

2

只是通過header('Content-Type: application/json');在你的代碼

<?php 
    if ($result=mysqli_query($conn,$sql)) 
    { 
     $rowcount=mysqli_num_rows($result); 
    } 
    header('Content-Type: application/json'); 
    echo json_encode($rowcount); 

也是在你的腳本

var maxqty; 
$.getJSON('http://localhost/karthi/test.php', function(jsonData) { 
maxqty = jsonData; 
console.log(jsonData); 
}); 

如果傳遞到服務器的任何值,值分配給數據

data = 'list'; 
var maxqty; 
    $.getJSON('http://localhost/karthi/test.php', data, function(jsonData) { 
    maxqty = jsonData; 
    console.log(jsonData); 
    }); 
+0

當我這樣做時,我仍然收到一個「Uncaught reference error:未定義數據」的錯誤。 – taurus

+0

請現在檢查@ user1234231 – karthickeyan

2

起初你需要t o在PHP代碼中添加標題。 header('Content-Type:application/json');

那麼問題是在jQuery中,您的代碼不知道什麼是

$ .getJSON 數據變量( '[在這裏或者PHP文件URL]',數據,功能(jsonData )

數據是將被髮送到服務器的參數,它可以是任何平面的文字或內容;完全分配給任何數據之前將它傳遞