Php 通过$迭代json。每个函数类型错误

Php 通过$迭代json。每个函数类型错误,php,javascript,jquery,json,each,Php,Javascript,Jquery,Json,Each,我从php得到的响应如下: {"success":false,"errors":{"category_id":"category id must not be empty","name":"name must not be empty","uri":"uri must not be empty","price":"price must not be empty","status":"status must not be empty"}} 并希望显示错误: form.submit(functio

我从php得到的响应如下:

{"success":false,"errors":{"category_id":"category id must not be empty","name":"name must not be empty","uri":"uri must not be empty","price":"price must not be empty","status":"status must not be empty"}}
并希望显示错误:

form.submit(function(ev) {
    ev.preventDefault();

    $('.help-inline').remove();

    var data = $(this).serialize();

    $.post($(this).attr('action'), {'data': data}, function(result) {

        if (result.success == true) {
            console.log('true');
        } else {
            $.each(result.errors, function(label, error) {
                console.log(label+' '+error);
            });
        }
    });
});
但是它抛出了我的
TypeError:e是未定义的

在旧版本上它可以工作,但在1.8.3上则不行。 我做错了什么

我的php代码是:

            $errors = $post->errors('');
            $this->response->body(json_encode(array(
                'success' => FALSE,
                'errors' => $errors,
            )));
$errors是关联数组:

array(5) (
    "category_id" => string(29) "category id must not be empty"
    "name" => string(22) "name must not be empty"
    "uri" => string(21) "uri must not be empty"
    "price" => string(23) "price must not be empty"
    "status" => string(24) "status must not be empty"
)

您的
结果.errors
是一个仅包含一个元素的数组,您希望使用
$进行迭代。每个
,因此只需替换以下行:

$.each(result.errors, function(label, error) {
对于这一个:

$.each(result.errors[0], function(label, error) {

这应该可以满足您的需要。

在JSON中,错误数组似乎只包含一个元素,该元素是具有属性的对象,请尝试使用:

$.each(result.errors[0], function(label, error) {

PHP和response似乎还可以,但我不知道在哪里可以说javascript将使用json数据类型。您可以在使用console.log(结果)代码时验证这一点。然后查看结果是对象还是字符串。作为

form.submit(function(ev) {
    ev.preventDefault();

    $('.help-inline').remove();

    var data = $(this).serialize();

    $.post($(this).attr('action'), {'data': data}, function(result) {
        console.log('Result is: ' + typeof(result));
        if (result.success === true) {
            console.log('true');
        } else {
            $.each(result.errors, function(label, error) {
                console.log(label+' '+error);
            });
        }
    });
}, "json");

发布您的php代码,因为我们必须查看服务器端如何处理请求。服务器代码已修改,TypeError仍然存在。我已经尝试过了,TypeError:result.errors未定义。您的jsbin链接在Chrome上运行良好,显示了预期的结果,没有javascript错误。你犯了什么错误?您使用的浏览器是什么?@UAMoto您的javascript已被缓存。重新加载。@eicto抱歉,我错误地认为jsbin链接是由UAMoto发布的,谢谢您发布。@UAMoto错误在哪一行?我在(e,t,r){var I=t.dir,s=…jquery.min.js(第2行)没有看到任何
e
变量在使用中。TypeError:e未定义…eturn t?u.length:u?nt.error(e):L(e,a).slice(0)}函数在(e,t,r){var I=t.dir,s=…jquery.min.js中没有任何代码会导致这种情况。不幸的是jquery/浏览器问题,除非您有任何其他Javascript破坏jquery。。