![](/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.