簡體   English   中英

PHP 返回 JSON 到 JQUERY AJAX

[英]PHP returning JSON to JQUERY AJAX CALL

我仍在努力了解 JQUERY、AJAX 和 PHP 的來龍去脈。

我現在可以調用 PHP OK,處理表單元素並發送 email,但我不處理返回到 AJAX。 我總是收到error:選擇器已激活,當我嘗試列出返回的假定 JSON 時,我得到信息,這顯然是錯誤的。

PHP 與假定 JSON 返回

<?php

touch('phpTouch.txt');
// process email
$email=1;
if ($email) {
    $value = array('return' => 1, 'msg1' => 'Message sent OK, we will be in touch ASAP');
} else {
    $value = array('return' => 0, 'msg1' => 'Message Failed, please try later');
}
$output = $json->encode($value);
echo $output;

?>

Javascript 和 AJAX

function submitForm(evt) {
    $('#msgid').html('<h1>Submitting Form (External Routine)</h1>');
    if ($('#formEnquiry').valid() ) {
        $("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
            $.ajax({
            url: "ContactFormProcess3.php",
            type: "POST",
            data: $('#formEnquiry').serialize(),
            dataType: "json",
            success: function (data) {
                alert("SUCCESS:");
                for(var key in data) {
                    $('#msgid').append(key);
                    $('#msgid').append('=' + data[key] + '<br />');
                }
            },
            error: function (data) {
                alert("ERROR: ");
                for(var key in data) {
                    $('#msgid').append(key);
                    $('#msgid').append('=' + data[key] + '<br />');
                }
            }
        });
    } else {
        $('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
    }
    evt.preventDefault();
};

假定的 JSON 數據列表

readyState=4
setRequestHeader=function (a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this}
getAllResponseHeaders=function (){return s===2?n:null}
getResponseHeader=function (a){var c;if(s===2){if(!o){o={};while(c=bF.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c}
overrideMimeType=function (a){s||(d.mimeType=a);return this}
etc etc 

如果有人能告訴我我犯了什么愚蠢的錯誤,那么我將不勝感激。

您可以通過這種方式在 PHP 中返回 json:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM