开发者

Ajax call doesn't work properly in Chrome and FF

I'm trying to change a div's content by calling a partial view with jQuery, from another partial view.

Here's the patial view From which I'm trying to invoke the second one:

<h2>Login</h2>
<div id="Bar">Content goes here
</div>
<div id="Register">Register</div>

And my jQuery:

$(document).ready(function () {
    $('#Register').click(function () {

        var resultHTML = jQuery.ajax({
            type: 'GET',
            url: 'AccountBar/Register'
        }).responseText;
        $('#Bar').html(resultHTML);       
    });
});

This works well in IE(9) but not in Chrome nor in FF - both just empty the "Bar" div.

When debugging in browser, it seems resultHTML is empty in both Chrome and FF (but in IE it's correct).

When debuggin开发者_运维问答g in VS, all clicks on register div call the correct action:

public PartialViewResult Register()
        {
            return PartialView();
        }

And the view:

@model PartialTry.Models.PasswordModel
    <h2>Register</h2> 

Any idea how to get Chrome and FF to change "Bar" div as well?

Thanks.


When you're doing this:

var resultHTML = jQuery.ajax({
    type: 'GET',
    url: 'AccountBar/Register'
}).responseText;
$('#Bar').html(resultHTML); 

IE9 is doing a little trickery here, blocking until the request completes (or caching it, depending on which build you're on) when accessing .responseText. The important thing to remember is it's an asynchronous call, meaning it goes off and makes the request...the result will be available later.

In this case the simplest approach is the .load() method just for this:

$('#Bar').load('AccountBar/Register');

This roughly translates into:

$.ajax({
    type: 'GET',
    url: 'AccountBar/Register'
    success: function(result) {
        $('#Bar').html(result);
    }
});

The alternative approach like that you're attempting is to make the request * synchronous* (please don't do this) by setting async: false on the $.ajax({}) call, like this:

var resultHTML = jQuery.ajax({
    type: 'GET',
    url: 'AccountBar/Register',
    async: false
}).responseText;

This will work...but it'll also lock up the browser while it runs, instead of causing no interruption and updating #Bar when complete...this is a much worse user experience, and best not to do it.


Have you tried waiting for a response via callback? For example:

$.ajax({
  type: 'GET', 
  url: 'AccountBar/Register',
  context: document.body,
  success: function(response) {
    $('#Bar').html(response);
  },
  error: function(response) {
    alert('oops, something went wrong!')
  }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜