且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jQuery Ajax将JSON发送到PHP服务器-JSON错误

更新时间:2023-01-01 16:55:40

我能够获取json对象并在php端对其进行解析.某些变量的名称可能有所不同,部分原因是其中一些是预先编写的代码.这是我采取的步骤.

I was able to get the json object and parse it on php side. Some variable might be named different, partly because some of it is pre-written code. Here are the steps I took.

文件夹结构

js/script.js
php/get_data.php
index.html

Index.html 基本形式.

<div id="feedback_panel" class="panel panel-default">
    <form id="feedbackform" name="feedbackform" method="post">
            <div class="form-group" id="email_wrapper" data-toggle="popover" data-container="body" data-placement="right">
                <label class="control-label" for="email">E-mail:</label>
                <input type="email" class="form-control" id="email" name="email" placeholder="email@example.com" required>
                <span class="help-block"> </span>
            </div>
            <div class="form-group" id="subject_wrapper" data-toggle="popover" data-container="body" data-placement="right">
                <label class="control-label" for="subject">Subject:</label>
                <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" required>
                <span class="help-block"> </span>
            </div>
            <div class="form-group" id="description_wrapper" data-toggle="popover" data-container="body" data-placement="right">
                <label class="control-label" for="message">message:</label>
                <textarea type="text" class="form-control" id="message" name="message" placeholder="message." required></textarea>
                <span class="help-block"> </span>
            </div>
            <button type="submit" id="feedback_submit" class="btn btn-success">Submit</button>
    </form>
</div>

script.js 提交后,收集数据并将其设置为对象,然后通过ajax发送到php.

script.js upon submit, gather data and set it to an object and send to php via ajax.

$(function() {
    // process the form
    $('#feedbackform').submit(function(event) {

        // get the form data - obj that will POSTED to get_data.php
        var formData = {
            'email'       : $('#email').val(),
            'subject'     : $('#subject').val(),
            'message'     : $('#message').val()
        };

        // process the forum
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'php/get_data.php', // the url where we want to POST
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
            encode      : true
        })
            // using the done promise callback
            .done(function(data) {
                // log data to the console so we can see
            if ( ! data.success) {
                console.log(data);
            } else {
                console.log(data);
            }

        });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});

get_data.php 从script.js接收数据,进行一些验证,然后发送并发送电子邮件.

get_data.php receives the data from script.js, do some validations, and then send and an e-mail.

<?php

$errors         = array();      // array to hold validation errors
$data           = array();      // array to pass back data

// validate the variables ======================================================
    // if any of these variables don't exist, add an error to our $errors array

$email;
$subject;
$message;


//check to see if the data exist, else write an error message,
function check_data(){
    $user_inputs = array();

    if (empty($_POST['email'])){
        $errors['email'] = 'Email is required.';
        return false;
    }else{
        $email = $_POST['email'];
        array_push($user_inputs,$email);
    }

    if (empty($_POST['subject'])){
        $errors['subject'] = 'subject is required.';
        return false;
    }else{
        $subject = $_POST['subject'];
        array_push($user_inputs,$subject);
    }

    if (empty($_POST['message'])){
        $errors['message'] = 'message is required.';
        return false;
    }else{
        $message = $_POST['message'];
        array_push($user_inputs,$message);
    }

    return $user_inputs;
}

//getting array of data from check_data
$verify_data = check_data();


// return a response ===========================================================

// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {

    // if there are items in our errors array, return those errors
    $data['success'] = false;
    $data['errors']  = $errors;
    echo json_encode($data);
} else {
    // show a message of success and provide a true success variable
    $data['success'] = $verify_data;
    $data['message'] = 'Success!';

    //if everything is good, sent an email.
    if($verify_data != false){
        send_email($verify_data);
    }
}

function send_email($info_data){
    // person who it going
    $to      = 'Email, Some <some_email@mailinator.com>';

    //subject of the  email
    $subject = $info_data[1];
    $result = str_replace(' ', '&nbsp;', $info_data[2]);
    $result = nl2br($result);
    $result = wordwrap($result, 70, "\r\n");

    //body of the email.
    $message = "<html><body>";
    $message .= "<p style = 'width: 400px;'>" . $result . "</p>";
    $message .= "<br/>";
    $message .= "</body></html>";
    $headers = "From: Email, Some <some_email@mailinator.com>" . "\r\n" . 'Reply-To: '. $info_data[0] . "\r\n" ."X-Mailer: PHP/" . phpversion();
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8";


    //sent mail: check to see if it was sent.
    if(mail($to, $subject, $message, $headers)){
        $data["went"] = "went";
        $data['message'] = 'Success!';
    }else{
        $data["went"] = "didn't go";
        $data['message'] = 'Sorry!';
    }

    // echo the log
    echo json_encode($data);

}

?>

请多多掩盖,如果您有任何疑问,请告诉我.我很乐意回答.

lot to cover, let me know if you any questions. I'll be happy to answer.