如何通过JavaScript发送跨域POST请求?
注意 - 它不应该刷新页面,然后我需要抓取并解析响应.
当我有这个代码
$.ajax({
type: 'POST',
//contentType: "application/json",
url: 'http://localhost:16329/Hello',
data: { name: 'norm' },
dataType: 'json'
});
Run Code Online (Sandbox Code Playgroud)
在Fiddler我可以看到以下原始请求
POST http://localhost:16329/Hello HTTP/1.1
Host: localhost:16329
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:14693/WebSite1/index.html
Content-Length: 9
Origin: http://localhost:14693
Pragma: no-cache
Cache-Control: no-cache
name=norm
Run Code Online (Sandbox Code Playgroud)
但我正在尝试的是将内容类型从application/x-www-form-urlencoded设置为application/json.但是这段代码
$.ajax({
type: "POST",
contentType: "application/json",
url: 'http://localhost:16329/Hello',
data: { name: 'norm' },
dataType: "json"
});
Run Code Online (Sandbox Code Playgroud)
生成奇怪的请求(我可以在Fiddler中看到)
OPTIONS http://localhost:16329/Hello …Run Code Online (Sandbox Code Playgroud) 我使用的是简单的jQuery
$.get( .... );
Run Code Online (Sandbox Code Playgroud)
这里没有获得GET响应,而是获得OPTIONS.(在firebug Net中检查)
相同的代码在Safari中正常工作.看起来像Firefox的一些问题.
解决此问题的任何解决方法/解决方案..
谢谢
Kurund
我从angular.js客户端向asp.net web api PUT方法发出以下请求:
var org = {
OrgId: 111,
name: 'testing testing'
};
$http.put("http://localhost:54822/api/data/putorganisation/1/", org).then(function(status) {
console.log("success PUT");
return status.data;
});
Run Code Online (Sandbox Code Playgroud)
但是获得以下errormsg(在fiddler中):
{"message":"The requested resource does not support http method 'OPTIONS'."}
Run Code Online (Sandbox Code Playgroud)
这是我的asp.net web api web.config文件的一部分:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type,x-xsrf-token,X-Requested-With" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<remove name="WebDAV" /> …Run Code Online (Sandbox Code Playgroud) 我正在努力成功地从网页上调用SOAP Web服务.Web服务是使用JAX-WS的Java Web服务.
这是我试图调用的Web方法:
@WebMethod
public String sayHi(@WebParam(name="name") String name)
{
System.out.println("Hello "+name+"!");
return "Hello "+name+"!";
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用JQuery库jqSOAPClient(http://plugins.jquery.com/project/jqSOAPClient)进行Web服务调用.
这是我用过的代码:
var processResponse = function(respObj)
{
alert("Response received: "+respObj);
};
SOAPClient.Proxy = url;
var body = new SOAPObject("sayHi");
body.ns = ns;
body.appendChild(new SOAPObject("name").val("Bernhard"));
var sr = new SOAPRequest(ns+"sayHi",body);
SOAPClient.SendRequest(sr,processResponse);
Run Code Online (Sandbox Code Playgroud)
似乎没有回应.在jqSOAPClient.js我记录xData.responseXML数据成员时,我得到'undefined'.在Web服务中,我看到了警告
2011年3月24日上午10:49:51 com.sun.xml.ws.transport.http.server.WSHttpHandler handleExchange警告:无法处理HTTP方法:选项
我也尝试过使用javascript库soapclient.js(http://www.codeproject.com/kb/Ajax/JavaScriptSOAPClient.aspx).我在这里使用的客户端代码是
var processResponse = function(respObj)
{
alert("Response received: "+respObj);
};
var paramaters = new SOAPClientParameters();
paramaters.add("name","Bernhard");
SOAPClient.invoke(url,"sayHi",paramaters,true,processResponse);
Run Code Online (Sandbox Code Playgroud)
我绕过了soapclient.js中获取WSDL的部分,因为它不起作用(我得到了:IOException: An established …
对于具有RESTful后端的webapp,我使用jquery的$ post将一些json发布到服务器.令我惊讶的是,json被填充在请求的表单数据的参数键中,而不是在请求体中.我可以想到其他一些方法,但问题是为什么它不能像我期望的那样工作.
在服务器上我使用scalatra并打印一些请求信息:
println("Request received:")
println(fromInputStream(request.getInputStream).getLines().mkString)
println("--------------")
println(request.getParameterMap.toString)
println("==============")
Run Code Online (Sandbox Code Playgroud)
现在一个简单的卷曲,我认为是正确的:
curl -X POST http://localhost:8080/x -H "Content-Type: application/json" -d '{"a":"b"}'
Run Code Online (Sandbox Code Playgroud)
生产:
Request received:
{"a":"b"}
-------------
{}
==============
Run Code Online (Sandbox Code Playgroud)
并用html + js来说明问题:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<body>
<button type="button" onclick="doPost()">
POST
</button>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function doPost() {
$.post("http://localhost:8080/x",
JSON.stringify({"a":"b"} ),
function(data) {});
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
生产:
Request received:
--------------
{{"a":"b"}=[Ljava.lang.String;@7a2897ac}
==============
Run Code Online (Sandbox Code Playgroud)
因此,如果我使用带有字符串化的json字符串和回调的$ post,我会将所有内容填充到单个参数键中.如果这是正常的,我想知道为什么,以及我应该如何在服务器上彻底解开这个问题.如果不正常,我想知道我应该怎么做才能使用$ post在响应体中获取它.
更新:现在有一个jquery的功能请求,以支持$ .post上的contentType
使用Meteor的速度框架登出测试信息的正确方法是什么?
我有一些mocha测试,我想从中输出一些值,我想如果输出最终会在速度窗口的日志部分结束,那就好了...但似乎没有任何文档地方?
似乎ASMX隐含地不允许OPTIONS动词.我发布这个问题是因为我正在使用POST的jQuery AJAX调用,它首先在发出POST动词**之前向服务器查询可用的OPTIONS.
默认情况下,Web.config将所有谓词映射到旧版ASMX,如此部分配置示例所示,因此所有内容都应正确路由:
<system.webServer>
<requestFiltering>
<verbs>
<add verb="OPTIONS" allowed="true"/>
<add verb="GET" allowed="true"/>
<add verb="POST" allowed="true"/>
</verbs>
</requestFiltering>
<handlers>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
Run Code Online (Sandbox Code Playgroud)
但是,对于OPTIONS请求,HTTP响应始终为405.例如,给出以下请求:
OPTIONS http://localhost:35920/MarkupTransfomer.asmx HTTP/1.1
Host: localhost:35920
Access-Control-Request-Method: POST
Run Code Online (Sandbox Code Playgroud)
并始终导致:
HTTP/1.1 405 Method Not Allowed
Server: Microsoft-IIS/7.5
X-AspNet-Version: 2.0.50727
Run Code Online (Sandbox Code Playgroud)
jQuery AJAX调用如下所示,来自最近一篇关于使用ASMX的Encosia博客文章的推荐:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:35920/MarkupTransfomer.asmx",
data: "{'hi'}",
dataType: "json"
});
Run Code Online (Sandbox Code Playgroud)
**注意:我不想将客户端切换为使用GET而不是POST.
摘要问题:我是否
可以配置ASP.NET以允许ASMX固有地处理OPTIONS请求而不会出现错误?
我可以找一种方法告诉你jQuery.ajax(..)不要在POST之前发出OPTIONS动词吗?
如果我不能从传统的ASMX那里得到什么,我还考虑了另外两个潜在的想法:
System.Web.IHttpHandler,将其粘贴在web.config …在你说另一个帖子(jQuery $ .ajax(),$ .post在Firefox中发送"OPTIONS"作为REQUEST_METHOD)之前,是的,它根本没有帮助,所以......
我正在使用Chrome开发最新版本,当我尝试将文件发送到这样的远程视频转换器服务的API时,它可以工作(一切都在coffeescript中)让我们调用此代码1:
json_string = getNewSignedParams()
xhr = new XMLHttpRequest
xhr.open('POST', some_url, true)
xhr.setRequestHeader("Cache-Control", "no-cache")
xhr.setRequestHeader("Content-Type", "application/octet-stream")
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
xhr.setRequestHeader("X-File-Name", some_file.name || some_file.fileName)
xhr.setRequestHeader("X-Query-Params", json_string)
xhr.send some_file
Run Code Online (Sandbox Code Playgroud)
以上返回200并且正常工作.但是我在页面上有jQuery,所以我想我会使用它,所以我有上面这样的jQuery版本.让我们称这个代码为2:
$.ajax
url: some_url
type: 'post'
data: some_file
processData: false
beforeSend: (xhr) ->
xhr.setRequestHeader("Cache-Control", "no-cache")
xhr.setRequestHeader("Content-Type", "application/octet-stream")
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
xhr.setRequestHeader("X-File-Name", some_file.name || some_file.fileName)
xhr.setRequestHeader("X-Query-Params", json_string)
success: ->
console.log 'success'
Run Code Online (Sandbox Code Playgroud)
我得到400(错误请求),说http://127.0.0.1:3000Access-Control-Allow-Origin不允许使用Origin.
但是得到这个,如果我取消注释代码1并注释掉代码2并刷新页面并上传文件,这将成功,并注释掉代码1并取消注释代码2并刷新页面并上传文件,NOW代码2赢了扔掉400 Bad请求错误!
但是,如果我关闭整个浏览器,并加载使用代码2的页面,无论我尝试多少次,上传文件都会给我400错误.然后,如果我执行上一段描述的内容,代码2将起作用!
还有一件事,Chrome控制台中的网络日志表示我使用代码2发出的请求将"OPTIONS"作为请求方法.而在代码1中,请求方法是"POST"
有谁知道这里发生了什么?
有人必须能够解释我在这里做错了什么!我正在尝试为Google App Engine应用程序创建最简单的AJAX帖子示例...而且我失败了!
这是app python
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from django.utils import simplejson
class EmailItem(db.Model):
email = db.StringProperty(multiline=False)
date = db.DateTimeProperty(auto_now_add=True)
class EmailList(webapp.RequestHandler):
def get(self):
self.response.out.write("You see nothing!")
def post(self):
eitem = EmailItem()
eitem.email = self.request.get("address")
eitem.put()
self.response.out.write("success")
application = webapp.WSGIApplication([('/', EmailList)])
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
这是jQuery
$.ajax({
type: "POST",
url: "myappengineURL",
data: "address=" + sVerifiedEmail,
success: function(msg) {
alert("Data Saved: " …Run Code Online (Sandbox Code Playgroud)