Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

javascript - Using WebSocket to reconnect to server

I have an experimental task implemented in javascript that posts its data to the server via an ajax POST request. This POST request is mandatory for compatability with other tools.

Saving data works fine when the task is finished quickly but over a certain time the server times out and when the tasks tries the POST request, I get a 400 error and nothing gets saved.

My question is can I combine this with a WebSocket and use it to reconnect to the server occasionally and still post my data with an ajax POST request? If so, how do I do this?

This is what my POST function looks like:

  $.ajax({

      type: 'POST',
      url: '/save',
      data: {'data': JSON.stringify(mainData)},

      success: function() {
          console.log('success');
          document.location = '/next'
      },

      // Endpoint not running, local save
      error: function(err) {

          if (err.status == 200) {
              document.location = '/next'
          }        

        }
    }); 

Optimally I would like to have something like this

      if (err.status == 200) {
          document.location = '/next'
      }  else if (err.status == 400) {
            // RECONNECT TO SERVER 
            // call ajax function again
      }      

I don't really have any experience with these tools, so any info will be much appreciated!

///////////////////// EDIT: ///////////////////////

I've been told that a more preferable option is to keep the connection constantly open with regular websocket requests. So a suggestion on how to do this would be appreciated as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...