How to wrap returned json data within a callback function and view it in the HTML page?

StackOverflow https://stackoverflow.com/questions/23100781

سؤال

I have created a WCF service which returns json data that can be viewed in the browser.. The data returned from the service and viewed in the browser is:

{"shipmentDetails":[{"Name":"AAA","Number":"123"},{"Name":"BBB","Number":"321"}]}

Now my goal is to wrap the above returned data in a callback function as follows in order to use the data as JSONP:

myCallback({"shipmentDetails":[{"Name":"AAA","Number":"123"},{"Name":"BBB","Number":"321"}]})

The interface I have implemented is:

  [ServiceContract]
         public interface IEIS
        {

            [OperationContract(Name = "getShipment")]
            [WebGet(ResponseFormat = WebMessageFormat.Json,
                       UriTemplate = "getShipment/{UserName}/{Password}")]
            Shipment getShipment(string UserName, string Password);

           [DataContract(Name = "Shipment")]
           [AspNetCompatibilityRequirements(RequirementsMode =  AspNetCompatibilityRequirementsMode.Allowed)]
           public class Shipment
           {
            [DataMember(Order = 0)]
            public shipmentDetails[] shipmentDetails { get; set; }
           }

          [DataContract(Name = "shipmentDetails")]
          [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
          public class shipmentDetails
          {
           [DataMember(Order = 0)]
           public string Name { get; set; }

           [DataMember(Order = 1)]
           public string Number { get; set; }
          }
        }

The actual data is retreived from the MySQL database.

My ultimate aim is to display the json data in the html page, for this I am using the following html but i have not suceeded with that. so now I am stepping up with wrapping the returned json data in a callback function for JSONP.

<html>
<head>
<title>JSON</title>
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js">
</script>

 <script language="javascript" type="text/javascript">
 $(document).ready(function(){
     $("testButton").click(function() {
        $.ajax({
           type: "GET",
           dataType: 'jsonp',
           contentType: "application/jsonp; charset=utf-8",
           url: "http://localhost:4148/EIS.svc/getShipment/json/data",
           success: function (data) {
               obj = eval('(' + data + ')');
               alert(obj);
               var innerHtml = "";
               document.getElementById('test').innerHTML=obj;
                      //'test' is ID of <label1>
                document.getElementById('testlab').innerHTML=obj.shipmentDetails[0].Name;
                     //'testlab' is ID of <label2>
               alert("JSON DATA");
               alert(obj.shipmentDetails[0].Number);
               },
               error: function (data) {

                    console.error(data);                
                },
                complete: function(data) { 
                    console.info(data);
                }

             });
         });
      });


</script>

</head>
<body>
<input type="button" id="testButton" value="GET JSON"/>
<label id="test"></label>
<label id="testlab"></label>
</body>
</html>

I am very new for this task, Please help me and give a valuable idea to wrap the data in a callback function and retrieve the data in HTML page.

Thanks in advance.

هل كانت مفيدة؟

المحلول

To wrap the returned data in a callback function, it needs to make changes in the url.

URL before wrapping the data is:

[http://localhost:4148/EIS.svc/getShipment/json/data]

URL after wrapping the data in a callback function is:

[http://localhost:4148/EIS.svc/getShipment/json/data?callback=jsonpexp]

After making the above changes in the URL the returned data is as follows:

jsonpexp({"shipmentDetails":[{"Name":"AAA","Number":"123"},{"Name":"BBB","Number":"321"}]});

To use the returned json data in HTML page:

Make the following changes in javascript

function getShipment() {
           $.ajax({
           type: "GET",
           dataType: 'jsonp',
           contentType: "application/jsonp; charset=utf-8",
           url: "http://localhost:4148/EIS.svc/getShipment/arun/arun?callback=jsonpexp",
           jsonpCallback: 'jsonpexp',
           success: function (data) {

               var innerHtml = "";
               document.getElementById('test').innerHTML=data.shipmentDetails[0].Name;;
                      //'test' is ID of <label1>
               document.getElementById('testlab').innerHTML=data.shipmentDetails[0].Number;
                     //'testlab' is ID of <label2>
               document.getElementById('test2').innerHTML=data.shipmentDetails[1].Name;;
               //'test2' is ID of <label3>
                 document.getElementById('testlab2').innerHTML=data.shipmentDetails[1].Number;
              //'testlab2' is ID of <label4>           
               },
               error: function (XMLHttpRequest, textStatus, errorThrown) {

                alert("Error while retrieval – " + XMLHttpRequest.responseText+":"+textStatus+":"+errorThrown);

                }

             });
         }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top