2016-11-07 14 views
0

ich habe eine jsp auf einem Server, der mir eine JSON wie folgt zurückgibt: { "link": "LINK_TEST", "title": "TITLE_TEST"}Parsing JSON-Daten von JSP

Ich versuche, diese zu erhalten Daten von einer Client-HTML-Seite, aber ich kann es tun.

dies ist der jsp Code:

<%@page contentType="text/html; charset=UTF-8"%> 
<%@page import="org.json.simple.JSONObject"%> 
<% 
    JSONObject json = new JSONObject(); 
    json.put("title", "TITLE_TEST"); 
    json.put("link", "LINK_TEST"); 
    out.print(json); 
    out.flush(); 
%> 

Die jsp sieht wie folgt aus: { "link": "LINK_TEST", "title": "TITLE_TEST"}

Und dies ist der Client-Seite Code:

<!DOCTYPE html> 
    <html> 
    <head>   
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> 
    <script> 
      $.ajax({ 
       url : 'http://my_ip:my_port/json.jsp', 
       data : { search: 'test' }, 
       dataType: 'json', 
       success : function(json) { 

       var ob = jQuery.parseJSON(json); 
       alert(ob.link+" "+ob.title); 

       document.getElementById("uno").innerHTML = ob.link; 
       document.getElementById("dos").innerHTML = ob.title; 
       } 

      }); 
    </script> 
    </head> 
    <body> 

    <h1 id="uno"></h1> 
    <h1 id="dos"></h1> 

    </body> 
    </html> 
+0

jQuery wird den JSON für Sie bereits deserialisieren, wenn Sie 'dataType:; json'' setzen, so dass Sie die Zeile 'var ob = jQuery.parseJSON (json);' Bitte überprüfen Sie die Konsole auf andere Fehler. Beachten Sie auch, dass jQuery 1.5.1 * sehr * veraltet ist. Sie sollten 1,12 am ältesten verwenden. –

+0

Dank @Rory McCrossan ich werde die Änderungen vornehmen – dbz

+0

Und was ist das Ergebnis? Was ist der Wert von Json? – AxelH

Antwort

0

dieses

//start ajax request 
    $.ajax({ 
     url: "data.json", 
     //force to handle it as text 
     dataType: "text", 
     success: function(data) { 

      //data downloaded so we call parseJSON function 
      //and pass downloaded data 
      var json = $.parseJSON(data); 
      //now json variable contains data in json format 
      //let's display a few items 
      for (var i=0;i<json.length;++i) 
      { 
       $('#results').append('<div class="name">'+json[i].name+'</>'); 
      } 
     } 
    }); 
+0

Ich weiß nicht warum, aber es funktioniert nicht mein Freund @ Albin – dbz