简体   繁体   中英

How to open a new page in jQuery Mobile from javascript function

I have a button in my html form.When i enter values in the textfield , a background operation is performed and data is sent to the server.But since this button already has an event (submit), how do i open a new page once that background operation is completed?

This is the button.

<a href="#" id="submit" data-role="button" data-inline="true"> Submit</a>

and in my javascript i have this function

$(document).ready( function() {

$("#submit").bind('click', function(event){
    doSomeBackgroundStuff();

});

This is happening from Page A , i want Page B to open when doSomeBackgroundStuff() finishes.

since this button already has an event (submit)

Use preventDefault or return false:

$(document).ready( function() {

$("#submit").bind('click', function(event){
     event.preventDefault(); //or just use : return false; at last  
     doSomeBackgroundStuff();

});

You have a few options.

First, working with what you have already, You could use a callback function for your bind event, and add window.open to load the new page, and simply pass in a url, or hardcode it.

Your jquery would look something like:

$(document).ready( function() {

$("#submit").bind('click', function(event){
    //fire AJAX request
    doSomeBackgroundStuff();

},function(){//call back function
window.open('http://www.yourURL.com');
});//end bind

});//end doc ready

Here is further reading on window.open - How to open a new HTML page using jQuery?

A second option is to use AJAX. You would setup an AJAX request for the new page, and use $.ajaxSend and $.ajaxComplete to fire functions before and after the request.

Your jquery would look something like:

//on button click
$('#submit').click(function(){
   doSomeBackgroundStuff();
});

//ajax start handler
$(document).ajaxStart(function(){
    //do stuff before AJAX request
});

//ajax complete
$(document).ajaxComplete(function(){
  //do stuff after AJAX request

});

A related question with a similar solution.

Global AJAX handlers

Hope this helps

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