使用Javascript使用JSON从字符串中获取数据

时间:2014-07-01 17:02:11

标签: c# javascript json vb.net

我需要你的帮助:我创建了一个Web服务,它返回一个干净的字符串 点击网址后<:p>

{
    "PersonID": 125,
    "Title": "Security Officer",
    "Company": "TSA",
    "CellNum": "423-915-3224",
    "EmergencyPhone": "",
    "Email": ""
}

如何使用JSON提取该字符串并获取数据?

我的WebService:

 <OperationContract()>
    <WebGet(ResponseFormat:=WebMessageFormat.Json, UriTemplate:="/getPersonInfo/?personID={personID}&companyCode={companyCode}", BodyStyle:=WebMessageBodyStyle.Bare)>
    Public Function getPersonInfo(ByVal personID As String, ByVal companyCode As String) As Stream
        Dim dba As New DBAccess
        Dim person As New PersonInfo
        Dim m_SelPerson As String = String.Empty
        Dim ds As DataSet = dba.GetPersonInfo(personID, companyCode)
        If Not ds Is Nothing Then
            Dim dr As DataRow = ds.Tables(0).Rows(0)
            person = New PersonInfo
            person.PersonID = Convert.ToInt32(dr("PersonID"))
            person.Company = dr("Company")
            person.Title = dr("Title")
            person.CellNum = dr("CellNum")
            person.EmergencyPhone = dr("EmergencyPhone")
            person.Email = dr("Email")
            Dim oSerilzer As New System.Web.Script.Serialization.JavaScriptSerializer
            m_SelPerson = oSerilzer.Serialize(person)
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8"
        End If
        Return New MemoryStream(Encoding.UTF8.GetBytes(m_SelPerson))
    End Function

JS功能:

function getPersonInfo(personID) {
        var json = '"http://122.123.1.118/GSWS/Service1.svc/REST/getPersonInfo/?personid=125&companycode=TSA&sensor=false"';
        obj = JSON.parse(json);
        alert(obj);
    }

1 个答案:

答案 0 :(得分:0)

<http>
<script src='http://code.jquery.com/jquery-1.11.1.min.js'></script>
<body>

<script>
    var url = "http://122.123.1.118/GSWS/Service1.svc/REST/getPersonInfo/?personid=125&companycode=TSA&sensor=false";
    $.getJSON( url, function( data ) {
        alert(data.PersonID);
    });
</script>

</body>
</html>