JSON 是適用于 Ajax 應(yīng)用程序的一種有效格式,原因是它使 JavaScript 對象和字符串值之間得以快速轉(zhuǎn)換。由于 Ajax 應(yīng)用程序非常適合將純文本發(fā)送給服務(wù)器端程序并對應(yīng)地接收純文本,相比不能生成文本的 API,能生成文本的 API 自然更可??;而且,JSON 讓您能夠處理本地 JavaScript 對象,而無需為如何表示這些對象多費心思。
XML 也可以提供文本方面的類似益處,但用于將 JavaScript 對象轉(zhuǎn)換成 XML 的幾個現(xiàn)有 API 沒有 JSON API 成熟;有時,您必須在創(chuàng)建和處理 JavaScript 對象時格外謹(jǐn)慎以確保所進(jìn)行的處理能與所選用的 XML 會話 API 協(xié)作。但對于 JSON,情況就大不相同:它能處理幾乎所有可能的對象類型,并會返回給您一個非常好的 JSON 數(shù)據(jù)表示。 因此,JSON 的最大價值在于可以將 JavaScript 真的作為 JavaScript 而非數(shù)據(jù)格式語言進(jìn)行處理。
您所學(xué)到的所有有關(guān)使用 JavaScript 對象的技巧都可以應(yīng)用到代碼中,而無需為如何將這些對象轉(zhuǎn)變成文本而多費心思。
1. 回車問題
JSON傳值的時候,如果有回車符就會掛的。我們可以使用正則來去掉回車符:
$str = preg_replace("'([\r\n])[\s]+'", "", $str); // 不用正則 $str = str_replace("\n","",$str);
轉(zhuǎn)出來的字符串就沒有回車符的困擾了。
順便記錄一個PHP過濾腳本:
<?php // $document 應(yīng)包含一個 HTML 文檔。 // 本例將去掉 HTML 標(biāo)記,javascript 代碼 // 和空白字符。還會將一些通用的 // HTML 實體轉(zhuǎn)換成相應(yīng)的文本。 $search = array ("'<script[^>]*?>.*?</script>'si", // 去掉 javascript "'<[\/\!]*?[^<>]*?>'si", // 去掉 HTML 標(biāo)記 "'([\r\n])[\s]+'", // 去掉空白字符 "'&(quot|#34);'i", // 替換 HTML 實體 "'&(amp|#38);'i", "'&(lt|#60);'i", "'&(gt|#62);'i", "'&(nbsp|#160);'i", "'&(iexcl|#161);'i", "'&(cent|#162);'i", "'&(pound|#163);'i", "'&(copy|#169);'i", "'&#(\d+);'e"); // 作為 PHP 代碼運行 $replace = array ("", "", "\\1", "\"", "&", "<", ">", " ", chr(161), chr(162), chr(163), chr(169), "chr(\\1)"); $text = preg_replace ($search, $replace, $document); ?>
2. HTML特殊字符
從服務(wù)器端以JSON格式將數(shù)據(jù)傳遞到客戶端后,通過JS顯示在HTML頁面時,有一些特殊字符不能直接顯示,如后臺傳遞過來的是 'msg #' 通過JS顯示在HTML頁面中時,顯示成了 msg # ,并不是msg #,這是由于<與>之間的內(nèi)容看作是HTML標(biāo)簽了,而以&開頭的 與#為HTML實體,所以顯示不正常。
解決辦法很簡單,在JS將其渲染到HTML頁面前轉(zhuǎn)換一下即可:
<script type="text/javascript"> var str = '<b>msg</b> #'; document.all.div1.innerHTML='<pre class="brush:php;toolbar:false">'+str+''; //js中的字符串正常顯示在HTML頁面中 String.prototype.displayHtml= function(){ //將字符串轉(zhuǎn)換成數(shù)組 var strArr = this.split(''); //HTML頁面特殊字符顯示,空格本質(zhì)不是,但多個空格時瀏覽器默認(rèn)只顯示一個,所以替換 var htmlChar="&<>"; for(var i = 0; i< str.length;i++){ //查找是否含有特殊的HTML字符 if(htmlChar.indexOf(str.charAt(i)) !=-1){ //如果存在,則將它們轉(zhuǎn)換成對應(yīng)的HTML實體 switch (str.charAt(i)) { case '<': strArr.splice(i,1,'<'); break; case '>': strArr.splice(i,1,'>'); break; case '&': strArr.splice(i,1,'&'); } } } return strArr.join(''); } alert(str.displayHtml()); document.all.div2.innerHTML=str.displayHtml();
3. escape()函數(shù)
該函數(shù)可以處理空格、斜線和其他任何可能影響瀏覽器的內(nèi)容,并將它們轉(zhuǎn)換成 Web 可用字符(比如,空格會被轉(zhuǎn)換成 %20,瀏覽器并不會將其視為空格處理,而是不做更改,將其直接傳遞到服務(wù)器)。之后,服務(wù)器會(通常自動)再把它們轉(zhuǎn)換回它們傳輸后的本來 “面目”。
var url = "nowamagic.php?people=" + escape(people.toJSONString()); request.open("GET", url, true); request.onreadystatechange = updatePage; request.send(null);
這種做法的缺點有兩個: 在使用 GET 請求發(fā)送大塊數(shù)據(jù)時,對 URL 字符串有長度限制。雖然這個限制很寬泛,但對象的 JSON 字符串表示的長度可能超出您的想象,尤其是在使用極其復(fù)雜的對象時更是如此。在跨網(wǎng)絡(luò)以純文本發(fā)送所有數(shù)據(jù)的時候,發(fā)送數(shù)據(jù)面臨的不安全性超出了您的處理能力。
簡言之,以上是 GET 請求的兩個限制,而不是簡單的兩個與 JSON 數(shù)據(jù)相關(guān)的事情。在想要發(fā)送用戶名和姓之外的更多內(nèi)容,比如表單中的選擇時,二者可能會需要多加注意。若要處理任何機(jī)密或極長的內(nèi)容,可以使用 POST 請求。
4. 引號問題
JSON中如果包含引號或雙引號,會破壞JSON的格式。有兩種方法可以解決。
在入庫的時候可以使用addslashes()函數(shù)處理一下字符串,給引號前加上斜杠。被改的字符包括單引號 (')、雙引號 (")、反斜線 backslash (\) 以及空字符NULL。
$text = addslashes($text); JavaScript的話,可以這樣: function valueReplace(v){ v=v.toString().replace(new RegExp('(["\"])', 'g'),"\\\""); return v; } var eValue = encodeURI($.trim(valueReplace(e.value)))
? ?

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

PHP provides the following functions to process JSON data: Parse JSON data: Use json_decode() to convert a JSON string into a PHP array. Create JSON data: Use json_encode() to convert a PHP array or object into a JSON string. Get specific values ??of JSON data: Use PHP array functions to access specific values, such as key-value pairs or array elements.

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

Parsing JSON data Parsing JSON data is a critical step in processing complex data. In Java, we can use the following methods: Use the Gson library: Gson is a widely used jsON parsing library that provides a concise and efficient api, as shown below: Gsongson=newGson();JsonObjectjsonObject=gson.fromJson(jsonString ,JsonObject.class); Using the Jackson library: Jackson is another popular JSON processing library that supports rich functionality and conversion to other formats (such as XML), as shown below: ObjectMappe

JSONFeed is a JSON-based RSS alternative that has its advantages simplicity and ease of use. 1) JSONFeed uses JSON format, which is easy to generate and parse. 2) It supports dynamic generation and is suitable for modern web development. 3) Using JSONFeed can improve content management efficiency and user experience.

RSS chose XML instead of JSON because: 1) XML's structure and verification capabilities are better than JSON, which is suitable for the needs of RSS complex data structures; 2) XML was supported extensively at that time; 3) Early versions of RSS were based on XML and have become a standard.
