jQuery/Ajax/PHP - 似乎无法弄清楚出了什么问题


jQuery/Ajax/PHP - cant seem to figure out what is wrong

由于某种原因,我正在处理的这个 ajax 调用在控制台日志中返回错误状态......我似乎想不通为什么,一切对我来说都是正确的!

阿贾克斯:

$(document).ready( function() {
    $('.load-more').click(function(e) {
        e.preventDefault();
        console.log('Starting AJAX');
        var $this = $(this);
        var load   = $this.data('current-page') + 1;
        var parent = $this.data('parent');
        var properties = {
            snippet: 'infiniteScroll',
               limit: 3,
               offset: 0,
               parents: 22,
               depth: 999,
               sortby: 'publishedon',
               showHidden: 1,
               debug: 1,
               tpl: 'infiniteHomePageTpl',
               };
          $this.data('current-page', load);
        $.ajax({
            type: "POST",
            url: "/ajax.processor",
            data: properties,
            cache: false,
               dataType: "json",
            success: function(response) {
                if(response.status == 'success'){
                    console.log('Success');
                }else if(response.status == 'error'){
                    console.log('data error');
                }else{
                    console.log('some other error');
                }
              },
              error: function(response){
                 console.log('an error has occurred' + response);
              },
        }); // ajax
    });
});// document ready

被调用的处理器:

<?php
// $modx->log(modX::LOG_LEVEL_ERROR,'Running ajax.processor, snippet = '.$_POST['snippet'].' formdata = '. print_r($_POST, TRUE));
$output = $modx->runSnippet($_POST['snippet'],array(
   'snippet' => $_POST['snippet'],
   'data' => $_POST
));
// set the header for the ajax call
$output =  json_encode($output);
header('Content-type: application/json');
$modx->log(modX::LOG_LEVEL_ERROR,'Should be json = '.$output);
echo $output;

处理器执行的代码:

<?php
    //$modx->log(modX::LOG_LEVEL_ERROR, 'Running infinitescroll snippet' . print_r($scriptProperties, TRUE));
    $output = array(
      'status' => 'success',
      'msg' => 'a message of some type',
      'whatever' => 'this is some data',
    );
    return $output;

处理器中的日志记录行会将 json 输出到日志中:

Should be json = {"status":"success","msg":"a message of some type","whatever":"this is some data"}

所以我的 JavaScript ~应该~ 恢复 JSON,但它没有达到成功条件,我在控制台日志中得到的只是:

an error has occurred[object Object]

我在这里做错了什么?

你需要json_encode php数组,正如Kaleb已经评论的那样。 http://php.net/manual/en/function.json-encode.php

所以你的代码应该是:

//$modx->log(modX::LOG_LEVEL_ERROR, 'Running infinitescroll snippet' . print_r($scriptProperties, TRUE));
$output = array(
  'status' => 'success',
  'msg' => 'a message of some type',
  'whatever' => 'this is some data',
);
$json = json_encode($output);
return $json;

我还建议您使用 Firebug 来监控您的 javascript,而不是记录控制台消息:http://getfirebug.com/

尝试使用HTTP客户端,如Postman(甚至cURL)来模拟你的AJAX调用。这使得检查响应的标头和内容变得容易。

此外,当调用错误处理程序时,第一个参数将始终是 XHR 对象。如果执行console.log(response);(不使用字符串强制转换),则应该能够检查其内容。不过,可能对您更有用的是其他两个参数:

错误 类型: 函数( jqXHR jqXHR, 字符串文本状态, 字符串 错误抛出 )

更多信息在jQuery.ajax文档中。

您实际上需要一个 json 内容类型标头并对输出进行编码:

<?php
header('Content-Type: application/json');
    //$modx->log(modX::LOG_LEVEL_ERROR, 'Running infinitescroll snippet' . print_r($scriptProperties, TRUE));
    $output = array(
      'status' => 'success',
      'msg' => 'a message of some type',
      'whatever' => 'this is some data',
    );
    echo json_encode($output);

如果您想知道为什么会发生这种情况,您可以使用$.ajax.fail()来期待errorThrown

$.ajax({
    type: "POST",
    url: "/ajax.php",
    data: properties,
    cache: false,
    dataType: "json",
success: function(response) {
//your code
},
error: function(response){
//your code 
},
}).fail(function(jqXHR,textStatus,errorThrown) {
    console.log(errorThrown);
});