car*_*ter 4 php ajax jquery json
jquery中的初始.ajax调用:
$.ajax({
type: 'post',
url: 'items_data.php',
data: "id="+id,
dataType: 'json',
success: function(data){
if(data){
make_item_rows(data);
}else{
alert("oops nothing happened :(");
}
}
});
Run Code Online (Sandbox Code Playgroud)
将简单的字符串发送到php文件,如下所示:
header('Content-type: application/json');
require_once('db.php');
if( isset($_POST['id'])){
$id = $_POST['id'];
}else{
echo "Danger Will Robinson Danger!";
}
$items_data = $pdo_db->query ("SELECT blah blah blah with $id...");
$result_array = $items_data->fetchAll();
echo json_encode($result_array);
Run Code Online (Sandbox Code Playgroud)
我正好抓住$ result_array并将其传递给另一个函数.我仔细检查确实返回了正确的值,因为我可以将结果回显到我的页面,它显示如下内容:
[{"item_id":"230","0":"230","other_id":"700"},{"item_id":"231","0":"231","other_id":"701"},{"item_id":"232","0":"232","other_id":"702"}]
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何迭代结果,所以我可以将值注入我的HTML中的表中.这是我的功能:
function make_item_rows(result_array){
var string_buffer = "";
$.each(jQuery.parseJSON(result_array), function(index, value){
string_buffer += value.item_id; //adding many more eventually
$(string_buffer).appendTo('#items_container');
string_buffer = ""; //reset buffer after writing
});
}
Run Code Online (Sandbox Code Playgroud)
我还尝试在$ .each函数中发出一个警告,以确保它发射了3次,就是这样.但是,我的代码中没有数据.尝试过其他一些方法也没有运气.
更新:我更改了我的代码以包含parseJSON,没有骰子.我的jquery文件中出现意外的令牌错误(当它尝试使用本机json解析器时).尝试添加json标头无效,同样的错误.jquery版本1.9.1.现在的代码应该在上面反映出来.
ala*_*arr 10
dataType:"JSON"在ajax调用中设置和回调.
例如:
$.ajax({
url: "yourphp.php?id="+yourid,
dataType: "JSON",
success: function(json){
//here inside json variable you've the json returned by your PHP
for(var i=0;i<json.length;i++){
$('#items_container').append(json[i].item_id)
}
}
})
Run Code Online (Sandbox Code Playgroud)
还请在PHP集中考虑JSON内容类型. header('Content-type: application/json');
| 归档时间: |
|
| 查看次数: |
52294 次 |
| 最近记录: |