简体   繁体   English

数组在jQuery中没有按预期运行

[英]Array not acting as expected in jQuery

I'm doing jQuery Ajax with PHP, and after jQuery passes some $_POST data to PHP, PHP validates those data, and prepares an array with all the errors, and once all validation is done, the count of error is found, and if it is greater than 0, the array is encoded in json and it is printed on the screen. 我正在使用PHP进行jQuery Ajax,并且在jQuery将一些$ _POST数据传递给PHP之后,PHP验证这些数据,并准备一个包含所有错误的数组,并且一旦完成所有验证,就会发现错误计数,如果它大于0,数组以json编码,并在屏幕上打印。 jQuery then grabs those data with 'success:' and it does it, but it doesn't act as expected. 然后,jQuery使用'success:'抓取这些数据并且它会这样做,但它没有按预期运行。

PHP file validating: PHP文件验证:

<?php
$messages = array();

if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['message'])) {
    if(empty($_POST['name'])) {
        $messages[] = "Please fill in the Name field.";
    }
    if(empty($_POST['email'])) {
        $messages[] = "Please fill in the Email field.";
    }
    if(empty($_POST['subject'])) {
        $messages[] = "Please fill in the Subject field.";
    }
    if(empty($POST['message'])) {
        $messages[] = "Please write your message in the Message field!";
    }

    if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $messages[] = "Invalid email entered!";
    }

    if(strlen($_POST['name']) > 30 || strlen($_POST['name']) < 3) {
        $messages[] = "Your name cannot be less than 3 characters or more than 30 characters.";
    }
    if(strlen($_POST['email']) > 30 || strlen($_POST['email']) < 3) {
        $messages[] = "Your email cannot be less than 3 characters or more than 30 characters.";
    }
    if(strlen($_POST['subject']) > 30 || strlen($_POST['subject']) < 3) {
        $messages[] = "The subject cannot be less than 3 characters or more than 30 characters.";
    }
    if(strlen($_POST['message']) > 2000 || strlen($_POST['message']) < 40) {
        $messages[] = "Your message cannot be less than 40 characters or more than 2000 characters.";
    }

    if(count($messages) > 0) {
        $messages['elements'] = count($messages);
        echo json_encode($messages);
    } else {

    }
}

jQuery code: jQuery代码:

$(document).ready( function() {
    $(document).on('click', '.contact_submit', function() {
        var name = $('input#name').val();
        var email = $('input#email').val();
        var subject = $('input#subject').val();
        var message = $('input#message').val();

        var Data = "name=" + name + "&email=" + email + "&subject=" + subject + "&message=" + message;

        $.ajax({
            type: "POST",
            url: "portal/_inc/frontend/form.php",
            data: Data,
            success: function(messages) {

                var Count = messages.length;
                $('.messages').empty();
                for(var i = 0; i < Count; i++) {
                    $('.messages').append('<li class"error">' + messages[i] + '</li>\n');
                }
            }
        });
        return false;
    });
});

All works fine, but my output is in 'char' format like one character at a time. 一切正常,但我的输出是'char'格式,一次只有一个字符。 Click here for a screen shot. 点击此处查看截屏。

It's because your response is a string, and you're iterating over a string. 这是因为你的响应是一个字符串,而你正在迭代一个字符串。

This PHP code: 这个PHP代码:

echo json_encode($messages);

encodes an object/array into a JSON string. 将对象/数组编码为JSON字符串。

And this JS code: 这个JS代码:

var Count = messages.length;

will just return the length of the whole string, not the number of individual objects within the returned JSON. 将只返回整个字符串的长度,而不是返回的JSON中单个对象的数量。


The simplest way to fix it is to parse the JSON in your success callback: 解决它的最简单方法是在成功回调中解析JSON:

var messageObject = JSON.parse(messages);

and now the variable messageObject will have the data in the format you expected. 现在变量messageObject将具有您期望的格式的数据。

Add dataType:'JSON' to your ajax request: dataType:'JSON'添加到您的ajax请求:

 $.ajax({
        dataType:'JSON',
        type: "POST",
        url: "portal/_inc/frontend/form.php",
        data: Data,
        .....

and add 并添加

 header('Content-type: application/json; charset=utf-8');

to your php so that the javascript knows how to handle the response 到你的PHP,以便javascript知道如何处理响应

EDIT 编辑

the problem is that the json response is an object, not array, which does not have a .length property. 问题是json响应是一个对象,而不是数组,它没有.length属性。

you'd be better to do it like this: 你最好这样做:

success: function(messages) {
      $('.messages').empty();
      $.each(messages,function(){
           $('.messages').append('<li class"error">' + this + '</li>\n');
               });
        }

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

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