2015-11-16 64 views
0

我已經構建了一個簡單的jQuery AJAX請求,用於查詢選定模板的數據庫,然後返回電子郵件主題和電子郵件正文並將其插入html輸入字段。這一切都很好。jQuery AJAX請求 - 處理來自PHP頁面的特殊字符

我剛剛注意到,當數據被插入到電子郵件正文中,它看起來像這樣的:

Dear Sally & John, thank you for your call today . . . 

代替:

Dear Sally & John, thank you for your call today . . . 

還有一些在電子郵件正文中的佔位符用戶通常會像這樣手動更換:

Dear <<dear>>, 

這些顯示爲:

Dear &lt;&lt;dear&gt;&gt; 

我使用PHP來查詢數據庫,並作爲JSON返回數據:

$templateDetails[] = array('templateBody' => $updatedTemplateBody); 
echo json_encode($templateDetails); 

下面是調用PHP請求腳本:

$(document).ready(function() { 
    $("#templateRef").change(function() { 
    var templateRef = $("#templateRef").val(); 
    var contactID = '<?php echo $contactID; ?>'; 
    $.post('getSMSTemplate.php', { 
     contactID: contactID, 
     templateID: templateRef 
    }, function(data) { 
     data = JSON.parse(data); 
     if (data.error) { 
     alert("error"); 
     $("#messageBody").html(''); 
     return; // stop executing this function any further 
     } else { 
     // console.log(data[0].templateBody); 
     $("#messageBody").val(data[0].templateBody); 
     } 

    }).fail(function(xhr) { 
     $("#messageBody").html(''); 
    }); 
    }); 
}); 

有一些功能我可以打電話來逃避這些角色?不知道這是用JavaScript還是PHP完成,或者從哪裏開始?

+0

你的'messageBody'是一個文本框還是一個'div'?因爲你使用'html()'用於'div'和'val()',它用於文本框。假設你的代碼正在工作,我認爲它是一個文本框,否則你不會看到任何結果。 –

回答

0

那些 「特殊字符」:他們實際上是HTML編碼的文本。問題不在於您在問題中發佈的代碼中。這裏是一個快速的證明:

var data = "<< me & you >>" 
 
$("#messageBody").val(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="messageBody" />

正如你所看到的代碼顯示「特殊字符」正確的,所以這個問題是由別的東西不知道關於你的項目的更多細節引起的,我只能想到兩種可能性。

1)將它們保存爲數據庫中的那樣,請檢查確認。在這種情況下,您可以使用htmlspecialchars_decode()解碼數據庫數據,然後將其作爲JSON使用,也可以使用$('<div/>').html(data[0].templateBody).text();在上面的jQuery中對其進行解碼。這是一個測試:當你生成的電子郵件

var data = "&lt;&lt; me &amp; you &gt;&gt;" 
 
data = $('<div/>').html(data).text(); 
 
$("#messageBody").val(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="messageBody" />

2)文字被編碼。如果來自未編碼數據庫的文本和您的messageBody正確顯示它,則需要檢查從messageBody獲取文本的代碼以生成電子郵件。如果您需要幫助,請在您的問題中發佈該代碼。

0

這部分:$("#messageBody").val(data[0].templateBody);可以改爲$("#messageBody").html(data[0].templateBody);

0

您可以使用htmlspecialchars_decode()在您的php中處理它的服務器,您只需在echo之前生成響應時調用它即可。

<?php 
$str = "<p>this -&gt; &quot;</p>\n"; 

echo htmlspecialchars_decode($str); 

// note that here the quotes aren't converted 
echo htmlspecialchars_decode($str, ENT_NOQUOTES); 
?> 

輸出:

<p>this -> "</p> 
<p>this -> &quot;</p> 

(摘自PHP手冊) https://secure.php.net/manual/en/function.htmlspecialchars-decode.php