【问题标题】:Sending json to php server using jquery ajax - json error使用 jquery ajax 将 json 发送到 php 服务器 - json 错误
【发布时间】:2016-01-19 18:09:27
【问题描述】:

我的网页上的表单有问题。我正在尝试使用 ajax 和 json 将表单值发送到 php 服务器,但我无法正确制作 json 对象。

我的 JS 代码

function sendJsonOpenPopout () {
    $('.submitBtn').click(function(e){
        e.preventDefault();

        var subject = $('.subject').val();
        var email = $('.email').val();
        var message = $('.message').val();

        var dataObject = {
            subject: subject,
            email: email,
            message: message
        }

        $.ajax({
        type: 'POST',
        url: '../../kontakt.php',
        contentType: "application/json",
        dataType: 'json',
        data: dataObject,

        success: function(data){
             alert('Items added');
        },

        error: function(){
            console.log('You have fail');
        }

        //success: function(){
            //var createdDiv = '<div class="divToBeCentered"><p class="dataText">Wiadomość została wysłana pomyślnie.\brDziękuję za kontakt.</p></div>';
             //$('body').append(createdDiv);
         //}
    });
});

我的 PHP 代码

<?php 
    $str_json = file_get_contents('php://input'); //($_POST doesn't work here)
    $response = json_decode($str_json, true); // decoding received JSON to array
    $subject = $response[0];
    $from = $response[1];
    $message = $response[2];

    $to = "lubycha@gmail.com"; 
    $subject = $_POST['subject'];
    $from = $_POST['email'];
    $message = $_POST['message'];
    $headers = "Content-Type: text/html; charset=UTF-8"; 
    mail($to,$subject,$message,$headers);
?>

我知道已经有人问过类似的问题,但答案对我没有帮助。

感谢您的帮助。

【问题讨论】:

  • url: '../../kontakt.php', 这是一条可疑的行,您将目录路径作为 url 提供它是错误的,只需使用 http://yourdomain/kontakt.php
  • 我很困惑为什么 $_POST 会是空的。 dataType 是预期的响应,而不是您提交的数据类型。您的类型设置为 POST .. 数据是作为 POST 发送到服务器的对象...我没有看到任何信息告诉我您正在主动将 json 数据作为字符串发送到服务器。所以你是说如果你var_dump($_POST)那它是空的?
  • 它没有帮助。我认为路径有问题,但我在几个网页上检查过它,我相信它应该可以正常工作。
  • 我在尝试将 json 发送到服务器时出现错误,“您失败了”功能。所以你是说我应该改变“帖子”类型?
  • 删除 contentType 因为您没有将数据序列化为 json 并且 $_POST 应该可以正常工作。还应该根据您的请求以 json 格式从服务器发回一些东西

标签: php jquery json ajax


【解决方案1】:

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

文件夹结构

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。

$(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 接收数据,进行一些验证,然后发送一封电子邮件。

<?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);

}

?>

很多内容,如果您有任何问题,请告诉我。我很乐意回答。

【讨论】:

  • 感谢您的帮助,非常有用。
  • @GimmeSomeCode 很高兴它对您有所帮助,欢迎您。您能否将其标记为正确或投票?或者如果您仍然需要帮助或对我的代码有疑问,请告诉我。
  • @GimmeSomeCode 谢谢!
  • Np 伙计!再次感谢您帮助我!
猜你喜欢
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-11
  • 2017-03-17
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多