zoukankan      html  css  js  c++  java
  • JavaScript中String类型转JSON

    JSON是一种便于操作使用的轻量级数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。官方网站:http://www.json.org

    很多时候我们需要组装字符串为json对象,首先要组合字符串,然后转换为json对象,如下面的例子:

    var convertStringToJSON = function(){
    var str="{'ID':12,'Name':'Tom','Age':21}";
    var stu = eval('('+str+')');
    alert(stu.Name);
    }

    上面代码执行后会弹出“Tom”,说明已经成功转换为json对象了,一个似乎很简单的问题,不过还是郁闷了半天才解决掉,还是记到blog上以加深印象,也希望能帮助遇到此问题的朋友早日解除郁闷。

    创建XMLHTTPRequest(摘自IBM Document:掌握Ajax系列)

    <script language="javascript" type="text/javascript">
    var request;
    function createRequest() {
    try {
    request = new XMLHttpRequest();
    } catch (trymicrosoft) {
    try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
    try {
    request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
    request = false;
    }
    }
    }
    if (!request)
    alert("Error initializing XMLHttpRequest!");
    }
    function getCustomerInfo() {
    createRequest();
    // Do something with the request variable
    }
    </script>



  • 相关阅读:
    笔记-归并排序
    Repeated Substring Pattern
    Assign Cookies
    Number of Boomerangs
    Paint Fence
    Path Sum III
    Valid Word Square
    Sum of Two Integers
    Find All Numbers Disappeared in an Array
    First Unique Character in a String
  • 原文地址:https://www.cnblogs.com/icerainsoft/p/2186147.html
Copyright © 2011-2022 走看看