简体   繁体   English

阿贾克斯总是会出错

[英]ajax always going to error

Im trying to learn to use ajax at the moment, but unfortunately I cannot get it to success . 我正在尝试学习使用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');
    }
    });

}); });

Here is the php function... 这是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));
    }

However this always makes a fail alert instead of a pass one. 但是,这总是发出失败警报,而不是通过警报。 Am I missing something obvious here? 我在这里错过明显的东西吗?

EDIT: Its finding the function ok, as in the console it is giving the correct response, 编辑:找到功能正常,因为它在控制台中给出了正确的响应,

ie

test 测试

test2 测试2

Thank you 谢谢

If your dataType is set to json, anything returned that is not JSON will cause the ajax call to error out. 如果您的dataType设置为json,则返回的任何非JSON内容都将导致ajax调用出错。 Try sending some json back to the script... {"test":"abc"} or similar. 尝试将一些json发送回脚本... {“ test”:“ abc”}或类似名称。 I see a couple of calls to echo in your code, for example. 例如,我看到了几个调用以在您的代码中echo

Not just this, but any PHP error/warning/notice printed to the browser will break calls. 不仅如此,打印到浏览器的任何PHP错误/警告/通知都将中断呼叫。

Hint: you can generate valid JSON from PHP variables using json_encode() . 提示:您可以使用json_encode()从PHP变量生成有效的JSON。

You cannot combine an existing query string with data. 您不能将现有查询字符串与数据结合使用。 Something like this should work (or at least be syntactically valid): 这样的事情应该起作用(或至少在语法上有效):

$.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');
    }
});

Also as was mentioned, anything that is not json will potentially cause an error, so you not echo those html components ... if anything, you print them. 同样如前所述,任何不是json的内容都可能会导致错误,因此您不会echo这些html组件...如果有,请print它们。

Also, as a side note your dataType should be done server side with a header('Content-type: application/json'); 另外,请注意,您的dataType应该在服务器端使用header('Content-type: application/json'); declaration in index.php rather than in your jQuery script. index.php而不是在jQuery脚本中声明。 Its guaranteed to be recognized as json that way, and also less Javascript code. 它保证以这种方式被识别为json,而且Javascript代码更少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM