![](/img/trans.png)
[英]Nginx rewriteurl from example.com/script.php?param=value to example.com/value
[英]Extracted json url from example.com/myjsonsql.php to jquery mobile fail to return value
我是一個新的PHP開發人員,我試圖創建一個簡單的系統,在該系統中,我使用php從mysql提取數據庫並在jquery mobile中使用json。
因此,在這種情況下,我在我的網站上創建了一個自定義.php json(從mysql中提取數據),並將其成功上傳到我的網站上,例如:www.example.com/mysqljson.php
這是我提取mysql數據的代碼
header('content-type:application/json');
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('mydb');
$select = mysql_query('SELECT * FROM sample');
$rows=array();
while($row=mysql_fetch_array($select))
{
$rows[] = array('id'=>$row['id'], 'id'=>$row['id'], 'username'=>$row['username'], 'mobileno'=>$row['mobileno'], 'gangsa'=>$row['gangsa'], 'total'=>$row['total']);
}
echo json_encode($rows);`
返回哪一個給我以下json @ http://i.imgur.com/d4HIxAA.png?1
一切似乎都很好,但是當我嘗試使用json網址在jquery mobile上進行提取時,它不會返回任何值。
我通過使用以下代碼提取json;
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
jsonCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
},
error: function(e) {
console.log(e.message);
}
});
}
json.id
@ #current_temp和json.id.username
@ #current_sum dint返回我的jquery移動頁面上的任何結果。
我懷疑我沒有正確提取json url,但是我不確定,有人可以幫助我確定問題嗎?
謝謝。
jsonp期望在要檢索的json中定義一個回調函數-有關詳細信息,請參見此處 。
您的數據打印屏幕實際上是普通的老式json,而不是jsonp。
所以我看到2個選項:
更改您的jquery請求,以期望使用普通的老式json(這假定客戶端和服務器位於同一域,否則會發生CORS錯誤),例如,
$.get(forecastURL) .then(function(json) { console.log(json); $("#current_temp").html(json.id); $("#current_summ").html(json.id.username); }) .fail(function(e) { console.log(e.message); });
首先,您不必使用jsonp來檢索JSON。 您可以做一個簡單的Ajax調用。 如果您的HTTP響應包含良好的Content-Type,則jQuery自動將您的json字符串轉換為json對象。 您在PHP調用中做到了這一點。
我認為您的問題來自您的JavaScript成功回調中的json數據分析。 生成的json是包含一些用戶對象的數組。 在您的代碼中,您無法處理數組的一項,但是可以直接在數組上調用.id或.username。 因此,javascript給您未定義的值。
這是一個顯示json數組的第一項(索引0)的數據的示例。 之后,您可以根據自己的目的選擇如何處理數組對象,但這是一個示例:
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
success: function(json) {
console.log(json);
// See, I use [0] to get the first item of the array.
$("#current_temp").html(json[0].id);
$("#current_summ").html(json[0].username);
},
error: function(e) {
console.log(e.message);
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.