【发布时间】:2018-04-19 21:45:15
【问题描述】:
我想做一个 ajax get 调用 我可以成功 console.log 结果而不将数据类型 json 放入 ajax
dataType: 'json',
当我没有它的 console.log 时,我得到了
{"id":"1","post_id":"748037498494861","post_title":"laptop","image1":"team217.jpg","price":"1234"}{"id":"2","post_id":"740811329642473","post_title":"remote control car","image1":"team522.jpg","price":"50"}{"id":"4","post_id":"316194613858174","post_title":"Ipad 3","image1":"team523.jpg","price":"400"}
但是我无法显示 json 数据 如果我把
dataType: 'json',
我的
console.log
为空 我不明白问题出在哪里
$(document).ready(function(){
var username = $("#usernameinfo").text();
$.ajax({
type:"GET",
url: "<?= base_url()?>"+"account/listings/more_user_ads",
data: {"username":username,"pid":"<?=$this->input->get('pid')?>"},
success: function(res){
console.log(res);
}
});
});
php
function more_user_ads(){
$post_id = $this->input->get('pid');
$username = $this->input->get('username');
$query = $this->get_where_custom('username', $username);
if($query->num_rows()>0){
foreach($query->result() as $row){
if($post_id != $row->post_id){
$result = array(
'id'=> $row->id,
'post_id'=> $row->post_id,
'post_title'=> $row->post_title,
'image1'=> $row->image1,
'price'=> $row->price,
'price'=> $row->price,
);
$res = json_encode($result);
echo $res;
【问题讨论】:
-
那不是有效的 JSON,你不会在循环中回显
json_encode调用 -
运行您的字符串:jsonlint.com。它不是有效的 json,所以你的 ajax 失败了。
-
我猜你的 PHP 需要运行
header("Content-type: application/json");;现在它正在发送恰好是 JSON 的纯文本。此外,您需要在循环内执行$res[] = $result;,然后在循环之后调用echo json_encode($res);一次。 -
感谢您提供有关将结果作为数组的信息,它确实 console.log 一个不同的结果,但它仍然不允许数据类型:'json' 那是随着听到的变化
-
还在上面的链接中重新测试了新的 json 它仍然在第 7 行给出错误???
标签: javascript jquery json ajax codeigniter