我想在JavaScript中使用XMLHttpRequest来POST一个包含文件类型输入元素的表单,这样我就可以避免页面刷新并获得有用的XML.
我可以在没有页面刷新的情况下提交表单,使用JavaScript将表单上的目标属性设置为MSIE的iframe或Mozilla的对象,但这有两个问题.小问题是目标不符合W3C(这就是为什么我在JavaScript中设置它,而不是在XHTML中设置它).主要问题是onload事件不会触发,至少不会触发OS X Leopard上的Mozilla.此外,XMLHttpRequest会产生更漂亮的响应代码,因为返回的数据可能是XML,而不是像iframe那样仅限于XHTML.
提交表单会产生如下HTTP的HTTP:
Content-Type: multipart/form-data;boundary=<boundary string>
Content-Length: <length>
--<boundary string>
Content-Disposition: form-data, name="<input element name>"
<input element value>
--<boundary string>
Content-Disposition: form-data, name=<input element name>"; filename="<input element value>"
Content-Type: application/octet-stream
<element body>
Run Code Online (Sandbox Code Playgroud)
如何获取XMLHttpRequest对象的send方法来复制上述HTTP流?
我正在尝试使用XMLHTTPRequest在twitter上获取更新.
var XMLReq = new XMLHttpRequest();
XMLReq.open("GET", "http://twitter.com/account/verify_credentials.json", false, "TestAct", "password");
XMLReq.send(null);
Run Code Online (Sandbox Code Playgroud)
但是,使用我的嗅探器,我看不到任何授权标头被传递.因此,我从Twitter获得了401错误响应.
正确输入帐户和密码.
有人试过吗?谁能给我一些指示?谢谢.
众所周知,在XHR(又名AJAX)Web应用程序中,没有为您的应用程序构建历史记录,单击刷新按钮通常会将用户移出他/她当前的活动.我偶然发现了location.hash(例如http://anywhere/index.html#somehashvalue)来规避刷新问题(使用location.hash通知你的应用程序它的当前状态并使用页面加载处理程序来重置该状态).这真的很好很简单.
这让我想到使用location.hash来跟踪我的应用程序的历史记录.我不想使用现有的库,因为它们使用iframe等.所以这是我的镍和硬币:当应用程序页面加载时我开始这样:
setInterval(
function(){
if (location.hash !== appCache.currentHash) {
appCache.currentHash = location.hash;
appCache.history.push(location.hash);
/* ... [load state using the hash value] ... */
return true;
}
return false;
}, 250
);
Run Code Online (Sandbox Code Playgroud)
(appCache是包含应用程序变量的预定义对象)想法是从哈希值触发应用程序中的每个操作.在体面的浏览器中,哈希值更改会在历史记录中添加一个条目,在IE(<= 7)中则不会.在所有浏览器中,向后或向前导航到具有其他哈希值的页面不会触发页面刷新.这就是间隔函数接管的地方.每次检测到哈希值更改(通过编程方式,或通过单击后退或前进)时,应用程序都可以采取适当的操作.应用程序可以跟踪它自己的历史记录,我应该能够在应用程序中显示历史记录按钮(特别是对于IE用户).
据我所知,这可以跨浏览器工作,并且在内存或处理器资源方面没有任何成本.所以我的问题是:这是否是管理XHR-apps历史的可行解决方案?优缺点都有什么?
更新:因为我使用我的自制框架,我不想使用现有的框架之一.为了能够在IE中使用location.hash并将其包含在历史中,我创建了一个简单的脚本(是的,它需要一个iframe),这可能对你有用.我在我的网站上发布它,随意使用/修改/批评它.
我一直在使用同步XMLHttpRequest,其responseType设置为"arraybuffer"很长一段时间来加载二进制文件并等到它被加载.今天,我收到了这个错误:"Die Verwendung des responseType-Attributes von XMLHttpRequest wird im synchronen Modus im window-Kontekt nichtmehrunterstützt." 大致转换为"不再支持在窗口上下文(?)中以同步模式使用XMLHttpRequest的responseType."
有谁知道如何解决这一问题?我真的不想对这样的事情使用异步请求.
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.responseType = 'arraybuffer';
Run Code Online (Sandbox Code Playgroud)
镀铬工作正常.
我只是想在控制器规范上测试ajax请求.产品代码如下.我正在使用Devise进行身份验证.
class NotesController < ApplicationController
def create
if request.xhr?
@note = Note.new(params[:note])
if @note.save
render json: { notice: "success" }
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
规格如下.
describe NotesController do
before do
user = FactoryGirl.create(:user)
user.confirm!
sign_in user
end
it "has a 200 status code" do
xhr :post, :create, note: { title: "foo", body: "bar" }, format: :json
response.code.should == "200"
end
end
Run Code Online (Sandbox Code Playgroud)
我希望响应代码为200,但它返回401.我想这肯定是因为rspec抛出的请求缺少authenticity_token或其他东西.我该如何存根?
任何帮助将不胜感激.
我正在使用Selenium WebDriver来抓取一个网站(例如,我也将抓取其他网站!),它具有无限滚动.
问题陈述:
向下滚动无限滚动页面,直到内容停止使用Selenium Web驱动程序加载.
我的方法: 目前我这样做 -
第1步:滚动到页面底部
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:window.onload=toBottom();"+
"function toBottom(){" +
"window.scrollTo(0,Math.max(document.documentElement.scrollHeight," +
"document.body.scrollHeight,document.documentElement.clientHeight));" +
"}");
Run Code Online (Sandbox Code Playgroud)
然后我等待一段时间让Ajax请求像这样完成 -
第2步:明确等待Ajax请求结束
了Thread.sleep(1000);
然后我给另一个java脚本来检查页面是否可滚动
第3步:检查页面是否可滚动
//Alternative to document.height is to be used which is document.body.clientHeight
//refer to https://developer.mozilla.org/en-US/docs/DOM/document.height
if((Long)js.executeScript("return " +
"(document.body.clientHeight-(window.pageYOffset + window.innerHeight))")>0)
Run Code Online (Sandbox Code Playgroud)
如果上述条件为真,那么我重复步骤1 - 3,直到步骤3中的条件为假.
问题:
我不想Thread.sleep(1000);在步骤2中给出,而是我想在后台Ajax请求结束时使用Java Script检查,如果步骤3中的条件为真,则进一步向下滚动.
PS:我不是页面的开发者所以我无法访问运行页面的代码,我可以在网页中注入java脚本(如步骤1和3中所示).并且,我必须在无限滚动期间为任何具有Ajax请求的网站编写通用逻辑.
我将感激有些人可以在这里休息一下!
编辑:好的,经过2天的努力,我发现我通过Selenium WebDriver抓取的页面可以包含任何这些JavaScript库,我将不得不根据不同的库进行池化,例如,使用jQuery api 的web应用程序,我可能正在等待
(Long)((JavascriptExecutor)driver).executeScript("return jQuery.active")
Run Code Online (Sandbox Code Playgroud)
返回零.
同样,如果Web应用程序使用Prototype JavaScript库,我将不得不等待
(Long)((JavascriptExecutor)driver).executeScript("return Ajax.activeRequestCount")
Run Code Online (Sandbox Code Playgroud)
返回零. …
我正在尝试将图像加载到canvas元素中,然后将数据拉出到toDataURL().
我的网站运行Ruby on Rails 2.3
我的图像来自aws s3.我有设置cors:
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Run Code Online (Sandbox Code Playgroud)
我有一个canvas元素:
<canvas id="explain_canvas"></canvas>
Run Code Online (Sandbox Code Playgroud)
好的,所以有些背景.我最初尝试使用这样的代码,其中drawing_image只是图像的url.
var outlineImage = new Image();
outlineImage.crossOrigin = '';
outlineImage.src = drawing_image;
outlineImage.onload = function() {
var canvas = document.getElementById('explain_canvas');
var context = canvas.getContext("2d");
context.drawImage(outlineImage, 10, 10, 600, 150);
}
Run Code Online (Sandbox Code Playgroud)
但那不是发送原始标题.所以我以为我会通过jquery尝试ajax调用
var outlineImage = new Image();
$(outlineImage).attr('crossOrigin', '');
$.ajax({
type: 'get',
url : drawing_image,
contentType: 'image/png',
crossDomain: 'true',
success: function() {
$(outlineImage).attr("src", drawing_image);
},
error: function() {
console.log('ah crap');
} …Run Code Online (Sandbox Code Playgroud) 我已经实现了这个脚本用于上传带有ajax的文件,它在浏览器以外的其他浏览器中工作得很完美,我注意到IE9不支持formData,更少,IE中的formData有什么替代品,我想用干净的javascript
function doObjUploadExplorer(url, lnk_id, file, progress, success, content, frm, div_dlg, start_func){
var file_input = null,
frm_data = new FormData(),
req;
try {
//firefox, chrome, safari etc
req = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer Browsers
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (document.getElementById(file)) {
file_input = document.getElementById(file);
for (var i = 0; i < file_input.files.length; ++i) {
frm_data.append(file, file_input.files[i]);
}
}
req.upload.addEventListener('progress', function(e) { //Event called while upload is in progress
if (progress !== undefined
&& e.lengthComputable) { …Run Code Online (Sandbox Code Playgroud) 当前设置
我有一个像这样的HTML表单.
<form id="demo-form" action="POST" method="post-handler.php">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething">Update</button>
</form>
Run Code Online (Sandbox Code Playgroud)
我可能在页面上有很多这些表单.
我的问题
如何异步提交此表单而不是重定向或刷新页面?我知道怎么用XMLHttpRequest.我遇到的问题是在javascript中从HTML中检索数据然后放入一个post请求字符串.这是我目前用于zXMLHttpRequest`的方法.
function getHttpRequest() {
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");
}
return xmlhttp;
}
function demoRequest() {
var request = getHttpRequest();
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
console.log("Response Received");
}
}
request.open("POST","post-handler.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("action=dosomething");
}
Run Code Online (Sandbox Code Playgroud)
例如,假设在demoRequest()单击表单的提交按钮时调用了javascript方法,如何从此方法访问表单的值,然后将其添加到XMLHttpRequest …
我试图使用try-catch语句来处理错误XMLHTTPRequest,如下所示:
var xhr = new XMLHttpRequest();
xhr.open('POST', someurl, true);
try{
xhr.sendMultipart(object);
}
catch(err){
error_handle_function();
}
Run Code Online (Sandbox Code Playgroud)
当抛出401错误时xhr.sendMultipart,error_handle_function没有被调用.知道如何解决这个问题吗?
谢谢!