简体   繁体   中英

How get JSON Response from Spring in Javascript

I need a little help, i send from my server Spring Boot a response in JSON after a POST with a form, after the sent of datas and response, the web open a Modal, i need to take URL Generated from the server and print in the Modal. The json is like this :

{ url: "/somethin/something/index.html" }

I did this little function in Javascript but return always null, i think because i dont return in createURL nothing, i should return or a Object with Json or only a string of the specific value of Json, how can i do? :

function createURL() {
    var xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var json = JSON.parse(this.responseText);
            return json.URL;
        } else {
            return "No URL Created";
        }
    }
}

Chrome give me also this error: Uncaught ReferenceError: createURL is not defined

I call this function in this way in modal:

<div class="modal-body">
                    <script>createURL();</script>
                </div>

put your function before calling or call your function after function definition

<div class="modal-body" id="myList">
</div>
 <script>
function createURL() {
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        var json = JSON.parse(this.responseText);
        var textnode = document.createTextNode(json.URL);         
        document.getElementById("myList").appendChild(textnode);
    } else {
        var textnode = document.createTextNode("No URL Created");         
        document.getElementById("myList").appendChild(textnode);

    }
  }
}

createURL();
</script>

I fixed in this way, this is my function, take the actual response if all its ok and return the json complete, you can use in any other function or script you want.

function getJSON(XMLHttpRequest) {
    var json;
        if (XMLHttpRequest.readyState==4 && XMLHttpRequest.status == 200) {
            json=JSON.parse(XMLHttpRequest.responseText);
        } else {
            json= "No JSON Complete";
        }
        return json;
}

As you do have a createURL() somewhere, you could read that error message as Uncaught ReferenceError: createURL is not defined yet . So make sure that the function definition is available by the time you want to use it. Function hoisting (the act of collecting function and var definitions to the beginning of a JavaScript scope) does not work between <script> tags, thus their order matters:

 <script> console.log("Trying something:"); try{ doSomething(); }catch(ex){ console.log("It did not work:",ex.toString()); } console.log("Trying something else:"); try{ doSomethingElse(); }catch(ex){ console.log("It did not work:",ex.toString()); } function doSomething(){ console.log("something"); } </script> <script> console.log("Trying something (second tag):"); try{ doSomething(); }catch(ex){ console.log("It did not work:",ex.toString()); } console.log("Trying something else (second tag):"); try{ doSomethingElse(); }catch(ex){ console.log("It did not work:",ex.toString()); } function doSomethingElse(){ console.log("something else"); } </script> 

Then comes the rest:

  1. <script> in HTML is not content-generation, so it does not behave like some special tags in template engines and server-side scripts (PHP, ASP, JSP). Whatever you produce in a <script> tag, it will not get displayed
  2. return -ing something from most event handler callbacks goes straight to the trash. Just like an onclick event handler, onreadystatechange (or onload ) does not expect getting an answer. Whatever you want to do with the JSON, you should do that in the event handler itself. Later you can deal with async stuff and promises, but for displaying it, well, just display it.

Combined together:

<script>
  function createURL() {
    var xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        var json = JSON.parse(this.responseText);
        urldiv.innerText=json.URL;
      } else {
        urldiv.innerText="No URL Created";
      }
    }
  }

  createURL();
</script>
<div class="modal-body" id="urldiv"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM