简体   繁体   中英

JS - Handle initial server response to display JSON

I am working on a webpage. I am doing the front end and my colleague is doing the back end and web-server. He's using golang to write the web-server. Right now, his handler for '/' requests (ie, if I am hosting it locally, just plain localhost - not localhost/foo, etc.) is to send me back an html template/static file, which gets displayed automatically (I don't handle his template in any way with my JS).

We are now moving the webpage over to a SPA , and we have decided that he sends me the html to display using JSON. I am capable of handling JSON which comes from AJAX requests, which is how I display data on every other url request (using jQuery - $.ajax().done() , etc.); however, he still sends me a template to handle '/' requests, as I do not send an AJAX request for that.

The code that is currently being sent over as a template is:

<!DOCTYPE html>
<html>
  <head>
    <!--head-stuff, this area is populated-->
  </head>
  <body>
    <!--body stuff, this area is populated-->
  </body>
</html>

As we want to move fully over to sending JSON, the plan is that the web-server would send me JSON on '/' requests (ie, the above template would be sent as JSON). I am trying to figure out how I would handle it (capture it - as it would be a response not connected to a request that "I" - ie my JS - invoked).

Is this even possible? Or would the initial send always have to be a static file/template (my Google searches have resulted in nothing).

If you need an address that you can enter into a browser or link to, it can't be just JSON.

JSON is just data, and a browser won't spontaneously do anything with it.

What you need is at least one HTML page (and most importantly in your case, the associated embedded or linked JS). The HTML page can be very basic and just load some JS (which could then load the rest of the JS, HTML, CSS, provided via JSON or other means), but it needs to exist, as it's one of the only ways to have the browser execute any code.

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