开发者

AJAX won't POST to URL

Im trying to build a simple AJAX script that uses a form to send parameters to the Tumblr API.

This is the current code:

<body>
<script type="text/javascript">
function ajaxFunction()
{
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var title = document.getElementById("title").value;
var body = document.getElementById("body").value;
var str = "&email=" + email + "&password=" + password + "&title=" + title + "&body=" + body;
//document.write(str);
var xmlhttp;
if (window.XMLHttpRequ开发者_运维技巧est)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.getElementById("suc").value.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","http://www.tumblr.com/api/write?generator=TumblWave&type=regular",true);
xmlhttp.send(str);
}
</script>
<form id="myForm">
Name: <input type="text" id="email" />
Password: <input type="password" id="password" />
Title: <input type="text" id="title" />
Body: <input type="text" id="body" />
<input type="submit" onclick="ajaxFunction();" />
<div id="suc"></div>
</form>
</body>
</html> 

Sorry for the mess.

Somehow, the XMLHttpRequest doesn't seem to pull through, since nothing ever enters Tumblr. However, when I remove the comments for "document.write(str)" it seems like everything is being fetched as it's supposed to from the forms and printed with the right commands.

You might notice on the URL on xmlhttp.open that I've already included two static parameters: the generator name and the type of post that should be sent to the Tumblr API.

I made this after a model on w3schools.com with only few modifications. Any help appreciated :)


You can't use xmlhttprequest to post to a different site you can only go to the same url that the page you're viewing is hosted on.

See also Cross-site XMLHttpRequest


xmlhttprequest ordinarily does not support cross domain requests.

You might want to use PHP cURL for some task like that

so you get your ajax to write to the php file that will

then run your cURL post to the tumblr.com resource


A workaround to the XMLHttpRequest domain restriction is to create a proxy page at your domain that will receive the request and the make the remote call for you.

For example, if you were using ASP.NET your xmlhttp object could call AjaxProxy.aspx on your site, and that page could use a WebClient object to post the data to tumblr.com.


Why are you using "POST" if you are appending the parameters to the URL? You could use "GET" instead.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜