我试图构建一个简单的Ajax脚本,它使用表单向TumblrAPI发送参数。这是当前的代码:
<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.XMLHttpRequest)
{
// 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>
不知何故,XMLHttpRequest似乎没有实现,因为没有任何东西进入Tumblr。 但是,当我删除“ document.write(str)”的注释时,似乎一切都从表单中获取,并使用正确的命令进行打印。
你可能会注意到,在xmlhttp.open上的URL上,我已经包含了两个静态参数:生成器名称和应发送到Tumblr API的帖子类型。
我是在w3schools.com上的一个模型上进行的修改。任何帮助都将不胜感激!
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.