weixin_33692284 2014-08-03 11:07 采纳率: 0%
浏览 42

Ajax发布方法错误

In the following example I am able to pass JSON representation of the country list and display it but I cannot display the message "Could not find any countries". Could you please check the code below:

Controller:

if ($this->model_abc->did_get_country_list($user_id)) {             
        $country["results"]= $this->model_abc->did_get_country_list($user_id);          
            echo json_encode($country);         
        }
        else {      
        $country = array('message' => "Could not find any countries" );
            echo json_encode($country);     
        }

JS file:

$.post('cont/get_country_list', function (country) {
    $.each(country.results, function(i, res) {
        var item = $('<div>'),               
        title = $('<h3>');
        title.text(res);
        item.append(title);
        item.appendTo($("#country_list_is_got"));
    });   
}, 
       "json").error(function() { 
           $( "#country_list_is_not_got").text(country.message);
       });

Update:

I changed my code as following and now I get thise error from console: Uncaught TypeError: Cannot read property 'length' of undefined.

JS file:

$.post('cont/get_country_list', function (country) {
    if (country.message !== undefined) {
        $( "#country_list_is_not_got").text(country.message);
    } else {
        $.each(country.results, function(i, res) {
             var item = $('<div>'),               
                 title = $('<h3>');
                 title.text(res);
                 item.append(title);
                 item.appendTo($("#country_list_is_got"));
        });  


 }
});
  • 写回答

2条回答 默认 最新

  • weixin_33725722 2014-08-03 11:15
    关注

    You're not setting an error reply code in the case where no countries are found, so it's not treated as an error by jQuery.

    else {
        header("HTTP/1.1 500 Error");
        $country = array('message' => "Could not find any countries" );
        echo json_encode($country);
    }
    

    Also, your error function needs to get the data from its parameter:

    .error(function(xhr) {
        country = $.parseJSON(xhr.responseText);
        $( "#country_list_is_not_got").text(country.message);
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵