簡體   English   中英

jQuery AJAX請求-處理特殊字符以響應PHP頁面

[英]jQuery AJAX Request - Handle special characters in response from PHP page

我建立了一個簡單的jQuery AJAX請求,該請求查詢數據庫以獲取選定的模板,然后返回電子郵件主題和電子郵件正文,並將其插入html輸入字段。 一切都很好。

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

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完成的,或者從何處開始?

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

您可以使用htmlspecialchars_decode()在php中在服務器端處理它,在生成響應之前echo呼JSON之前將調用它。

<?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 Manual) https://secure.php.net/manual/zh/function.htmlspecialchars-decode.php

那些“特殊字符”:它們實際上是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()你之前到數據庫的數據進行解碼echo它作為JSON,或者您可以在上面的jQuery使用它進行解碼$('<div/>').html(data[0].templateBody).text(); 這是一個測試:

 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抓取文本的代碼以生成電子郵件。 如果您需要幫助,請在您的問題中張貼該代碼。

暫無
暫無

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

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