开发者

jQuery AJAX call not working in Webkit

I've run into a strange issue with Webkit based browsers (both Safari and Chrome - I'm testing on a Mac) and I am not sure what is causing it. Here's a small script I've created that replicates the issue:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function doRequest() {
  document.test.submit();
  $.ajax({
    type: "GET",
    cache: false,
    url: 'ajax.php?tmp=1',
    success: doSuccess
  });
}
function doSuccess(t_data,t_status,req) {
  alert('Data is: '+ t_data +', XMLHTTPRequest status is: '+ req.status);
}
</script>
</head>

<body>
<form name="test" method="post" action="ajax.html" enctype="multipart/form-data">
<input type="file" name="file_1">
<br><input type="button" value="upload" onclick="doRequest();">
</form>
</body>
</html>

ajax.php is:

<?php
echo $_REQUEST['tmp'];
?>

This works as is on Firefox, but the XMLHTTPRequest status is 开发者_开发技巧always "0" on both Safari and Chrome. If I remove this line:

document.test.submit();

then it works, but of course the form is not submitted. I've tried changing the form submit button from "button" to "submit", but that also prevents it from working on Safari or Chrome.

What I am trying to accomplish is:

  • submit the form
  • call another script to get status on the file being uploaded via the form (it's for a small upload progress meter).

Any help is really appreciated - I'm hopeful it is just a quirk I'm not familiar with.

Thanks!

  • Brian


Simply put: you cannot upload files using AJAX.

There are nice plugins such as jquery form that will handle this automatically (by creating a hidden iframe and performing the real file upload).

I think FireFox has a native file upload API but if you want a cross browser solution you will need to take a look at some plugins. Using a flash upload is another solution.


My experience while developing a similar upload checking tool1 is that you should use both success: .. and complete: ... They would probably do the exact same thing in your code and you can have them call the same function. complete: gets called when the request finishes, success: when a request succeeds. Thus maybe:

function doRequest() {
  document.test.submit();
  $.ajax({
    type: "GET",
    cache: false,
    url: 'ajax.php?tmp=1',
    complete: doSuccess,
    success: doSuccess
  });
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜