简体   繁体   中英

How to receive response on client side?

I have this form to upload an xml file to server, I am using fiddler to monitor each req and resp. So the server sends me a small xml and i would like to receive it in my javascript as XMLHttpRequest makes it happen

Note: I am uploading a file so enctype="multipart/form-data"

var client;
var url_action = "/csm/create.action";
var dataString;

if (window.XMLHttpRequest) {
    client = new XMLHttpRequest();
} else {
    client = new ActiveXObject("Microsoft.XMLHTTP");
}
if (client.readyState == 4 && client.status == 200) {
    alert(client.responseTest);
}
client.open("POST", url_action, true);
client.setRequestHeader("enctype", "multipart/form-data");
client.send();

My question is how can i receive the response from server side to JS variable. In the above code XMLHttpRequest i don't think i can send a multipart request (file upload). So any alternative is welcome. Whichever solution provides me a response is good. Here is what i am doing, to submit the form. Thanks :)

var url_action="/csm/create.action";
 $('#mainForm').attr('action', url_action);
 $('#mainForm').submit();

Updated with solution

$(data).find('com\\.abc\\.db\\.ConfigInfo').each(function(){
        cfgid=$(this).find('cfgId').text();
        cfgname=$(this).find('cfgName').text();
        filename=$(this).find('fileName').text();
        timestamp=$(this).find('updateDate').text();

        alert(cfgid+", "+cfgname+", "+filename+", "+timestamp);

        });

You have jQuery available so don't ever create XHR objects manually. Besides that, you cannot use AJAX for file uploads unless you don't care about compatibility with certain browsers.

Last but not least, you want to use the jQuery form plugin which will automatically fallback to a hidden iframe and a regular form if there is a file input in the form. Note that you need to wrap your JSON response in <textarea></textarea> for it to work properly though. See http://jquery.malsup.com/form/#file-upload for details. If you want to return XML you don't need to wrap it though - it should work fine without any server-side changes.

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