what is wrong with my http request in javascript?
I want to send a message to the server comprises of a few different sections. The goal is to send some x-www-form-urlencoded info with an image. I tried do sth similiar to this: http://en.wikipedia.org/wiki/MIME#Multipart_messages
This is my js function to do that:
function sendPage() {
var source = document.getElementById("pageContaine开发者_高级运维r")
var serializer = new XMLSerializer
if (!source.hasChildNodes()) {
alert("nie ma nic do wysłania")
return
}
var DOMNodeInString = "content=" + escape(serializer.serializeToString(source))
// sendToServer("savePage.php", true, handleAndShow, DOMNodeInString);return
xhttp.open("POST", "savePage.php", true)
var boundary = "xxx"
var body = "--" + boundary + "\r\n"
var file = document.getElementById("imgSource").files[0]
//wysyłam obrazek
if (file) {
var reader = new FileReader()
reader.readAsBinaryString(file)
body += "Content-Disposition: form-data; name='upload'; filename='" + file.name + "'\r\n"
body += "Content-Type: application/octet-stream\r\n\r\n"
body += reader.result + "\r\n"
body += "--" + boundary + "\r\n"
}
//wysyłam pozostałe pola formularza
body += "Content-Type: multipart/x-www-form-urlencoded \r\n\r\n"
body += DOMNodeInString
body += "\r\n--" + boundary + "--"
xhttp.setRequestHeader("Content-Type", "multipart/mixed; boundary=" + boundary)
xhttp.onreadystatechange = handleAndShow
alert(body)
xhttp.send(body)
}
however, the function doesn't work. My php script is unable to receive $_POST["content"]. What should I change to improve the js script?
It is not possible to upload a file using an XMLHttpRequest. You'll need to use Flash/Java or create a hidden iframe and do an actual submit. I'd suggest using a javascript plugin for "AJAX" file upload.
Apart from @tvanfosson answer, you are missing a creation of the xhttp object:
var xhttp = new XMLHttpRequest();
Use any debugger to see that the JS works without exceptions...
精彩评论