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 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加