2015-08-14 169 views
0

我的PHP函數來處理Ajax請求爲什麼我得到這個奇怪的JSON作爲輸出?

$nameMap = array('name' => 'Name', 'email' => 'Email Address', 'phone' => 'Phone Number', 'comments' => 'Comments'); 
// https://css-tricks.com/sending-nice-html-email-with-php/ 
$headers = "MIME-Version: 1.0\r\nContent-Type: text/html; charset=ISO-8859-1\r\n"; 
function contact () 
{ 
    global $nameMap, $headers; 
    $emailMsg = '<html><body><h3>Someone submitted a contact form ...</h3><table>'; 
    foreach ($_POST as $key => $value) if (array_key_exists($key, $nameMap)) $emailMsg .= '<tr><td><b>' . $nameMap[$key] . ':</b></td><td>' . $value . '</td></tr>'; 
    $emailMsg .= '</table></body></html>'; 
    if (mail("[email protected]","A Comment Was Submitted",$emailMsg,$headers)) 
    { 
     echo json_encode(array('succeeded' => true, 'msg' => 'Your comment was submitted successfully!')); 
    } 
    else 
    { 
     echo json_encode(array('succeeded' => false, 'msg' => 'There was a problem with the info you submitted.'));  
    } 
} 

,我的JavaScript是

   $('.contact-form .contact-submit-btn').click(function(e){ 
        formdata = new FormData($(this).closest('.contact-form')[0]); 
        formdata.append('action', 'contact'); 
        $.ajax({ 
         url: ajaxurl, 
         type: 'POST', 
         data: formdata, 
         async: false, 
         success: function (retobj) { 
          console.log(JSON.stringify(retobj)); // TEST 
          if (retobj.succeeded) 
          { 
           $('.contact-form h1').text('Your email was submitted successfully!');  
           $('.contact-form input[type="text"]').hide();      
          } 
          else 
          { 
           $('.contact-form h1').text('Your email was not submitted successfully!'); 
          } 
         }, 
         error: function() { 
          // haven't decided what to do yet 
         }, 
         cache: false, 
         contentType: false, 
         processData: false 
        });    
       }); 

並進入PHP腳本的else塊時(我不知道該if塊因爲我沒有能夠進去那裏哈哈)我看到

"\r\n\r\n0" 

打印到控制檯,而我期望看到

{"succeeded":true,"msg":"There was a problem with the info you submitted."} 

這些字符都來自哪裏?尤其是0 ...自從我開始學習PHP以來,我總是得到一個0添加到我的回調對象的末尾。

+1

所以開始調試:垃圾你的代碼調試輸出和看看事情在哪裏/何時執行。 –

+1

你爲什麼要用'json.stringify'? –

+0

嘗試將標題替換爲'header('Content-Type:application/json');'編輯:實際上,請嘗試設置標題,因爲該標題僅用於郵件。 – Berriel

回答

0

你的PHP沒有返回任何東西。

試試這個: 修改內容類型爲application/JSON

$headers = "MIME-Version: 1.0\r\nContent-Type: application/json; charset=ISO-8859-1\r\n"; 

,這增加了盡頭......

echo '{"succeeded":true,"msg":"There was a problem with the info you submitted."}'; 
相關問題