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 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64