【问题标题】:How to correctly receive a JSON response from AJAX (Javascript to PHP)如何正确接收来自 AJAX 的 JSON 响应(Javascript 到 PHP)
【发布时间】:2014-09-17 21:03:20
【问题描述】:

我的 script.php 文件将一些变量(从 HTML 表单中提取)发送到我的 email.php 文件。

这个文件然后将所有这些变量保存到一个 MYSQL 数据库中,作为回报还收集一个“订单 ID 号”(从 mysql_insert_id 收集),如下所示:

$order_id = mysql_insert_id();

然后将 $order_id 返回 传递给 script.php,后者将产品详细信息提交给 Paypal。目前,我希望 Paypal 的项目名称为“订单 ID:#$order_id”。

但是,我似乎无法将所有变量发送到 script.php,然后正确获取订单 ID。

我经常在 Google Chrome 控制台中收到“无法读取未定义的属性 'order_id'”错误,但是现在我从 JQuery 1.10.1 库中触发了这段代码(也在 Google Chrome 控制台中观察到)

// Uppercase the type
        s.type = s.type.toUpperCase();

这会导致以下错误:未捕获类型错误:对象 1 没有方法“toUpperCase”。

这是我的代码。我了解 mysql 已贬值,但我想在进行任何升级之前实现它。 ;)

SCRIPT.PHP

$('#submit').click(function(){ // 执行检查以确保已选择所有下拉选项。 // 验证成功,现在填充贝宝表单的可变部分
$('#emailBuyer').val($('#email_paypal').val());

    var host     = $(location).attr('host');
    var protocol = $(location).attr('protocol');        
    var pathname = $(location).attr('pathname');

    var returnPath          = pathname.replace("removed","removed");
    var cancelReturnPath    = pathname.replace("removed","removed");
    var returnPathUrl       = protocol + "//" + host + returnPath + $('#email_paypal').val();
    var cancelReturnPathUrl = protocol + "//" + host + cancelReturnPath + $('#email_paypal').val();     

    $('#returnPath').val(returnPathUrl);        
    $('#cancelReturnPath').val(cancelReturnPathUrl);        

    // Send the email. It needs to have the async=false as the form is tried to redirect to paypal before the email is sent!
    jQuery.ajaxSetup({async:false});
    $.get( controllerDir + 'email.php', {
    email: $('#email_paypal').val(),
    type: 1,
    question_one: $("#question_one option:selected").text(),
    question_two: $("#question_two option:selected").text(),
    question_three: $("#question_three option:selected").text(),
    question_four: $("#question_four option:selected").text(),
    question_five: $("#question_five option:selected").text(),
    question_six: $("#question_six option:selected").text(),
    question_seven: $("#question_seven option:selected").text(),
    question_eight: $("#question_eight option:selected").text(),
    question_nine: $("#question_nine option:selected").text(),
    question_ten: $("#question_ten option:selected").text(),
    amount: $('#amount').val(),
    shipping: $('#shipping').val(),
    total: $('#total').val(),
    contentType: "application/json",
    dataType: "json",
    success: function (data) {
    var myData = jQuery.parseJSON(data);
    console.log(mydata['orderid']);
        if (myData.orderid == '0') {
            alert('FAILED');
            $('#item_name').val( order_id + 'FAILED' + '');
        } else {
        var order_id = myData.orderid;
        $('#item_name').val( order_id + 'SUCCESS' + '');
        }
    }
    });
    jQuery.ajaxSetup({async:true});
});

EMAIL.PHP

    <?php
header('Content-Type: text/html');
 //Define Variables
 //User ID for remote email server
    $user_id = "REMOVED";  // Reece
    $question_one = $_GET['question_one'];
    $q1 = ltrim($question_one, "0123456789., ");
    $question_two = $_GET['question_two'];
    $q2 = ltrim($question_two, "0123456789., ");
    $question_three = $_GET['question_three'];
    $q3 = ltrim($question_three, "0123456789., ");
    $question_four = $_GET['question_four'];
    $q4 = ltrim($question_four, "0123456789., ");
    $question_five = $_GET['question_five'];
    $q5 = ltrim($question_five, "0123456789., ");
    $question_six = $_GET['question_six'];
    $q6 = ltrim($question_six, "0123456789., ");
    $question_seven = $_GET['question_seven'];
    $q7 = ltrim($question_seven, "0123456789., ");
    $question_eight = $_GET['question_eight'];
    $q8 = ltrim($question_eight, "0123456789., ");
    $question_nine = $_GET['question_nine'];
    $q9 = ltrim($question_nine, "0123456789., ");
    $question_ten = $_GET['question_ten'];
    $q10 = ltrim($question_ten, "0123456789., ");
    $amount = $_GET['amount'];
    $shipping = $_GET['shipping'];
    $total = $_GET['total'];
    $type  = $_GET['type'];    
    $order = $_GET['order'];
    $date = date('m/d/Y');
    $email_paypal = $_GET['email'];

    // Upload to database first. All credentials are correct,
// as when the "success" part of the ajax call (script.php) is removed, everything is uploaded perfectly.
 mysql_connect("CORRECT WEBHOST", "CORRECT USER", "CORRECT PASS") or die(mysql_error()); 
 mysql_select_db("CORRECT DB") or die(mysql_error()); 
 mysql_query("CORRECT QUERY"); 
 $order_id = mysql_insert_id();

switch($type) {
        case "1" :
            $name     = "Order $order_id Placed on $date";
            $comments = "(UNPAID) $q1, $q2, $q3, $q4, $q5, $q6, $q7, $q8, $q9, $q10"; 
            break;
        case "2" :
            $name     = "Order Paid on $date";
            $comments = "(PAID) $order";
            break;
        case "3" :
            $name     = "Order Cancelled on $date";
            $comments = "(CANCELLED) $order";
            break;          
        default :
            $name     = "$email_paypal $date";
            $comments = "Form Error. Unable to process email.";
    } 
    // Then send an email.

    $payload = "user_id=$user_id&form_id=2&name=$name&email=$email_paypal&comments=$comments";

    $curl_connection = curl_init("REMOVED");
    curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36");
    curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_connection, CURLOPT_POST, true);
    curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $payload);
    // NOTE: Error messages using an echo cannot be placed anywehere in this file. It distracts JSON and will make the Order ID variable unobtainable.
    header('Content-Type: application/json');
echo json_encode(array("orderid" => "$order_id","email" => "$email_paypal"));
?>

【问题讨论】:

    标签: javascript php ajax json paypal


    【解决方案1】:

    我认为你做得对。您不必将标题设置为要返回的 json。如果您将dataType 设置为json,则jQuery 将期望数据为json,如果php 返回的数据不是json,它将由jQuery AJAX 的错误函数处理。

    你可以替换这个

    header('Content-Type: application/json');
    echo json_encode(array("orderid" => "$order_id","email" => "$email_paypal"));
    

    die( json_encode(array("orderid" => "$order_id","email" => "$email_paypal")) );
    

    请注意,我使用了die,这是因为我不希望在输出json、额外的whitespaces 或其他可能在响应后打印的文本后运行任何其他文本可能会弄乱json 响应.所以为了安全起见。

    因此您也可以在success function 中跳过这一行

    var myData = jQuery.parseJSON(data);
    

    它将是 json

    这甚至不是问题,而只是减少代码行数的建议

    $question_one = $_GET['question_one'];
        $q1 = ltrim($question_one, "0123456789., ");
        $question_two = $_GET['question_two'];
        $q2 = ltrim($question_two, "0123456789., ");
        $question_three = $_GET['question_three'];
        $q3 = ltrim($question_three, "0123456789., ");
        $question_four = $_GET['question_four'];
        $q4 = ltrim($question_four, "0123456789., ");
        $question_five = $_GET['question_five'];
        $q5 = ltrim($question_five, "0123456789., ");
        $question_six = $_GET['question_six'];
        $q6 = ltrim($question_six, "0123456789., ");
        $question_seven = $_GET['question_seven'];
        $q7 = ltrim($question_seven, "0123456789., ");
        $question_eight = $_GET['question_eight'];
        $q8 = ltrim($question_eight, "0123456789., ");
        $question_nine = $_GET['question_nine'];
        $q9 = ltrim($question_nine, "0123456789., ");
        $question_ten = $_GET['question_ten'];
        $q10 = ltrim($question_ten, "0123456789., ");
    

    这可以替换为

    但如果可以将变量更改为 question_1、question_2 等等

    我会循环执行此操作

    for( $i = 1 ; $i <=10;$i++ ) {
        $qVar = "q".$i;
        $questionVar = "question_" . $i;
        $$questionVar = $_GET[ $questionVar ];
        $$qVar = ltrim( $$questionVar, "0123456789., ");
    
    
    }
    

    这样您就可以在四行中设置变量,并且可以将它们作为 $q1、$q2..so 和 $question_1、$question_2 进行访问

    但这只是我。我喜欢循环:)

    【讨论】:

    • 我想我会保存循环的使用,直到我得到这个排序;)它仍然不起作用。我已经更新了 script.php 代码。我注意到整个 ajax 调用一定是失败的,因为它没有插入到数据库中。当我删除“成功:等”时插入工作......难道我正在使用 $.get ?而不是 $.ajax?任何帮助,将不胜感激! ;)
    • 您将用户 1 作为类型参数。 type: 1,我从来没有用过。我什至不确定它是否有效。我认为应该是type : "post"type : "get"。尝试改变它。
    • 我对代码感到困惑。而不是调用这些两次jQuery.ajaxSetup({async:true}); 你可以用 async:false 发出一个 ajax 请求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多