开发者

post xml as a binary file using javascript

I'm trying to write something that can post xml, as a binary file to an external URL (which I have no control over) in JavaScript. I have Y开发者_如何学运维UI3 available to me. And probably jQuery if I needed it.

Any ideas? Everything I've looked at seems to be about receiving xml, rather than posting it.

Edit: The external url is an advertising bot, the xml essentially describes what sort of ad I want to get back.

I'm forced to post as binary. I've tested using-

<form enctype="multipart/form-data" action="http://something.com" method="post">
<input name="anything" type="file">something</file>
<input type="submit">
</form>

and that works. I just need to implement in js. Edit #2

My solution (couldn't get it formatted properly)-

var AdManager = { getRandomBoundary : function(){ var today = new Date; return '---' + today.getTime(); }, fetch : function(){ var boundary = this.getRandomBoundary(); var xhr = new XMLHttpRequest; var CRLF = "\r\n";

    xhr.open('POST', 'http://url.com', true);
    xhr.onreadystatechange = function(){
        if (xhr.readyState === 4)
        {
            //Parse xml(badly)
            var splitter = xhr.responseText.split('<responsecontent>');
            var allAds = '';
            for (var i= 1; i< splitter.length; i++)
            {
                var tempAd = splitter[i].split('</responsecontent>');
                allAds += tempAd[0];
            }
            //Html is returned encoded, so decode.
            jQuery('#results').html(jQuery("<div/>").html(allAds).text());
        }
    };

    xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);

    var mimeReq = "--" + boundary + CRLF;
    mimeReq += 'Content-Disposition: form-data; name="arbitrary"; filename="arbitrary.xml"' + CRLF;
    mimeReq += 'Content-Type: application/octet-stream' + CRLF + CRLF;
    mimeReq += '<?xml version=\"1.0\" encoding=\"utf-8\"?><adrequestpacket responsemarkup=\"wml\" test=\"0\" xmlns=...'+ CRLF;
    mimeReq += "--" + boundary + "--" + CRLF;

    xhr.send(mimeReq);
}

}; `


I think I understand what your asking, but if I'm totally on the wrong track, the below may appear a little patronising, so apologies in advance...

If all you want to do is send an XML file to a known URL via AJAX its fairly simple in javascript with no lovelies like jQuery etc. I am assuming you have already generated the XML file and have it stored as string variable somewhere.

The below code is a bit messy and fairly basic, but hopefully it should point you in the right direction. There are probably better ways of fetching an AJAX object if you search for them, but this is a method I have used for ages and never really have any problems with.

You will need to write some code to parse the server response to determine whether data was accepted or not - see comments in code for where you would do this. The ajaxObj.status and ajaxObj.responseText properties will be your friends here.

function postXMLToServer (serverURL, xmlStr) {

  // Declare some variables
  var activeXModes, i, ajaxObj, aSync, contentType;

  // Set this to false to perform the request synchronously (i.e. execution will block until request has completed)
  aSync = true;

  // 'application/octet-stream' is treated as raw binary data by any sensible server.
  // It might make more sense to use 'text/xml' or some variant depending on your application
  contentType = 'application/octet-stream';

  // Fetch an AJAX object
  activeXModes = ["Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
  if (window.ActiveXObject) { // Try ActiveX (for IE)
    for (i = 0; i < activeXModes.length; i++) {
      try {
        ajaxObj = new ActiveXObject(activeXModes[i]);
      } catch (e) {}
    }
  } else if (window.XMLHttpRequest) { // For Mozilla, Safari etc
    ajaxObj = new XMLHttpRequest();
  } else { // No AJAX
    alert('AJAX is not supported in your browser');
    return;
  }

  // Open connection to server
  ajaxObj.open('POST',serverURL,aSync);

  // Set some request headers - you might be able to get away with not doing this, but it
  // should be considered good practice, especially when doing POST requests
  ajaxObj.setRequestHeader('Content-Type',contentType);
  ajaxObj.setRequestHeader('Content-Length',xmlStr.length);

  // Set a callback for asynchronous requests (not called if aSync = false)
  ajaxObj.onreadystatechange = function () {
    if (ajaxObj.readyState == 4) {

      // parse the server response here

    }
  };

  // Send the request
  ajaxObj.send(xmlStr);

  // if aSync = false, parse the server response here

}

// Example of how to use the function
var myXMLStr = '<?xml version="1.0" encoding="iso-8859-1" ?>\n<toplevel>\n<lowerlevel anattribute="a value">An inner value</lowerlevel>\n</toplevel>';
var myURL = 'http://sub.domain.tld/path/to/document.ext?getparameter=somevalue';

postXMLToServer(myURL,myXMLStr);


It's not entirely clear what you want. Everything in the computer is represented in binary. So when you post an XML document over to http://something.com, the it's the binary representation of the characters in the XML file that is being transmitted.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜