简体   繁体   English

如何在Javascript中从Spring获取JSON响应

[英]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. 我需要一点帮助,我从服务器Spring Boot用表单发送POST后以JSON格式发送JSON响应,在发送数据和响应后,Web打开一个Modal,我需要使用从服务器生成的URL并打印模态。 The json is like this : json是这样的:

{ 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? 我在Javascript中做了这个小功能,但始终返回null,我想因为我不返回createURL一无所有,所以我应该返回一个带有Json的对象,或者只返回一个Json特定值的字符串,我该怎么办? :

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 Chrome也给我这个错误:Uncaught ReferenceError:未定义createURL

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. 我以这种方式修复了,这是我的函数,如果一切正常,则返回实际响应,并返回完整的json,您可以在所需的任何其他函数或脚本中使用。

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 . 当你这样做有一个createURL()的地方,你可以读取错误消息未捕获的ReferenceError:createURL 尚未确定 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: 函数提升(将functionvar定义收集到JavaScript作用域的开始)在<script>标记之间不起作用,因此它们的顺序很重要:

 <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). HTML中的<script>不是内容生成的,因此它的行为不像模板引擎和服务器端脚本(PHP,ASP,JSP)中的某些特殊标记。 Whatever you produce in a <script> tag, it will not get displayed 无论您在<script>标记中产生什么,它都不会显示
  2. return -ing something from most event handler callbacks goes straight to the trash. return -ing大部分事件处理程序回调的东西径直到垃圾桶。 Just like an onclick event handler, onreadystatechange (or onload ) does not expect getting an answer. 就像onclick事件处理程序一样, onreadystatechange (或onload )不会期望得到答案。 Whatever you want to do with the JSON, you should do that in the event handler itself. 无论您想对JSON做什么,都应该在事件处理程序本身中完成。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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