ajax总是会出错

时间:2013-04-15 13:54:49

标签: php javascript jquery ajax

我现在正试图学习使用ajax,但遗憾的是我无法将其发送到success

$('.engineering-services').live('click', function() {     
$.ajax({
    url: 'index.php?route=information/information/homepage_info',
    type: 'post',
    data: {info_description : 'test'},
    dataType: 'json',
    success:    function(json){
    alert('pass');
    },
    error: function(json) {
    alert('fail');
    }
    });

});

这是php函数......

    public function homepage_info() {
    $json = array();
    if (isset($this->request->post['info_description'])) {  
    echo $this->request->post['info_description'];
    echo '<br /> test2';
    }
    $this->response->setOutput(json_encode($json));
    }

然而,这总是会发出失败警报而不是通过警报。 我错过了一些明显的东西吗?

编辑:它发现函数正常,就像在控制台中它给出正确的响应一样,

即。

测试

TEST2

谢谢

2 个答案:

答案 0 :(得分:1)

如果您的dataType设置为json,则返回的非JSON 的任何内容将导致ajax调用错误输出。尝试将一些json发送回脚本... {“test”:“abc”}或类似的。例如,我在您的代码中看到了对echo的几次调用。

不仅如此,打印到浏览器的任何PHP错误/警告/通知都会中断调用。

提示:您可以使用json_encode()从PHP变量生成有效的JSON。

答案 1 :(得分:0)

您无法将现有查询字符串与数据组合在一起。像这样的东西应该起作用(或至少在语法上有效):

$.ajax({
    url: 'index.php',
    type: 'post',
    data: {information:'information/information/homepage_info',info_description:'test'},
    dataType: 'json',
    success:function(json){
        alert('pass');
    },
    error:function(json) {
        alert('fail');
    }
});

同样如上所述,任何不是json的东西都可能导致错误,所以你不echo那些html组件......如果有的话,你print

另外,作为旁注,您的dataType应该在服务器端完成,并在header('Content-type: application/json');中使用index.php声明,而不是在您的jQuery脚本中。它保证以这种方式被识别为json,也减少了Javascript代码。

相关问题