jQuery 如何在jsonp ajax调用中使用类型:“POST”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4508198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:22:42  来源:igfitidea点击:

How to use type: "POST" in jsonp ajax call

jqueryjsonphttp-post

提问by Manoj Singh

I am using JQuery ajax jsonp. I have got below JQuery Code:

我正在使用 JQuery ajax jsonp。我有以下JQuery 代码:

 $.ajax({  
        type:"GET",        
        url: "Login.aspx",  // Send the login info to this page
        data: str, 
        dataType: "jsonp", 
        timeout: 200000,
        jsonp:"skywardDetails",
        success: function(result)
        { 
             // Show 'Submit' Button
            $('#loginButton').show();

            // Hide Gif Spinning Rotator
            $('#ajaxloading').hide();  
         } 

    });  

The above code is working fine, I just want to send the request as "POST"instead of "GET", Please suggest how can I achieve this.

上面的代码工作正常,我只想将请求作为“POST”而不是“GET”发送,请建议我如何实现这一点。

Thanks

谢谢

回答by Nick Craver

You can't POST using JSONP...it simply doesn't work that way, it creates a <script>element to fetch data...which hasto be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.

您不能使用 JSONP 进行 POST ......它根本不能那样工作,它创建一个<script>元素来获取数据......它必须是一个 GET 请求。除了发布到您自己的域作为代理发布到另一个域之外,您无能为力……但是用户将无法直接执行此操作并查看响应。

回答by Pratik Butani

Use jsonin dataTypeand send like this:

使用jsondataType发送这样的:

    $.ajax({
        url: "your url which return json",
        type: "POST",
        crossDomain: true,
        data: data,
        dataType: "json",
        success:function(result){
            alert(JSON.stringify(result));
        },
        error:function(xhr,status,error){
            alert(status);
        }
    });

and put this lines in your server side file:

并将此行放在您的服务器端文件中:

if PHP:

如果 PHP:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');

if java:

如果Java:

response.addHeader( "Access-Control-Allow-Origin", "*" ); 
response.addHeader( "Access-Control-Allow-Methods", "POST" ); 
response.addHeader( "Access-Control-Max-Age", "1000" );

回答by Tgr

Modern browsers allow cross-domain AJAX queries, it's called Cross-Origin Resource Sharing(see also this documentfor a shorter and more practical introduction), and recent versions of jQuery support it out of the box; you need a relatively recent browser version though (FF3.5+, IE8+, Safari 4+, Chrome4+; no Opera support AFAIK).

现代浏览器允许跨域 AJAX 查询,它被称为跨域资源共享(另请参阅此文档以获得更简短和更实用的介绍),并且最新版本的 jQuery 开箱即用;不过,您需要一个相对较新的浏览器版本(FF3.5+、IE8+、Safari 4+、Chrome4+;没有 Opera 支持 AFAIK)。

回答by thdoan

If you just want to do a form POST to your own site using $.ajax()(for example, to emulate an AJAX experience), then you can use the jQuery Form Plugin. However, if you need to do a form POST to a different domain, or to your own domain but using a different protocol (a non-secure http:page posting to a secure https:page), then you'll come upon cross-domain scripting restrictions that you won't be able to resolve with jQuery alone (more info). In such cases, you'll need to bring out the big guns: YQL. Put plainly, YQL is a web scraping language with a SQL-like syntax that allows you to query the entire internet as one large table. As it stands now, in my humble opinion YQL is the only [easy] way to go if you want to do cross-domain form POSTing using client-side JavaScript.

如果您只想使用$.ajax()(例如,模拟 AJAX 体验)对您自己的站点执行表单 POST ,那么您可以使用jQuery 表单插件。但是,如果您需要向不同的域或您自己的域执行表单 POST 但使用不同的协议(将非安全http:页面发布到安全https:页面),那么您将遇到跨域脚本限制您将无法单独使用 jQuery 解决(更多信息)。在这种情况下,你需要拿出大枪:YQL. 说白了,YQL 是一种 Web 抓取语言,具有类似 SQL 的语法,允许您将整个互联网作为一个大表进行查询。就目前而言,在我看来,如果您想使用客户端 JavaScript 进行跨域表单发布,YQL 是唯一 [简单] 的方法。

More specifically, you'll need to use YQL's Open Data Tablecontaining an Executeblock to make this happen. For a good summary on how to do this, you can read the article "Scraping HTML documents that require POST data with YQL". Luckily for us, YQL guru Christian Heilmann has already created an Open Data Table that handles POST data. You can play around with Christian's "htmlpost" table on the YQL Console. Here's a breakdown of the YQL syntax:

更具体地说,您需要使用包含执行块的YQL 的开放数据表来实现这一点。有关如何执行此操作的良好总结,您可以阅读文章“使用 YQL 抓取需要 POST 数据的 HTML 文档”。幸运的是,YQL 大师 Christian Heilmann 已经创建了一个处理 POST 数据开放数据表。您可以在YQL 控制台上使用 Christian 的“htmlpost”表。以下是 YQL 语法的细分:

  • select *- select all columns, similar to SQL, but in this case the columns are XML elements or JSON objects returned by the query. In the context of scraping web pages, these "columns" generally correspond to HTML elements, so if want to retrieve only the page title, then you would use select head.title.
  • from htmlpost- what table to query; in this case, use the "htmlpost" Open Data Table (you can use your own custom table if this one doesn't suit your needs).
  • url="..."- the form's actionURI.
  • postdata="..."- the serialized form data.
  • xpath="..."- the XPathof the nodes you want to include in the response. This acts as the filtering mechanism, so if you want to include only <p>tags then you would use xpath="//p"; to include everything you would use xpath="//*".
  • select *- 选择所有列,类似于 SQL,但在这种情况下,列是查询返回的 XML 元素或 JSON 对象。在抓取网页的上下文中,这些“列”通常对应于 HTML 元素,因此如果只想检索页面标题,则可以使用select head.title.
  • from htmlpost- 查询什么表;在这种情况下,请使用“htmlpost”开放数据表(如果此表不适合您的需要,您可以使用您自己的自定义表)。
  • url="..."- 表单的actionURI。
  • postdata="..."- 序列化的表单数据。
  • xpath="..."-要包含在响应中的节点的XPath。这充当过滤机制,因此如果您只想包含<p>标签,则可以使用xpath="//p"; 包括您将使用的所有内容xpath="//*"

Click 'Test' to execute the YQL query. Once you are happy with the results, be sure to (1) click 'JSON' to set the response format to JSON, and (2) uncheck "Diagnostics" to minimize the size of the JSON payload by removing extraneous diagnostics information. The most important bit is the URL at the bottom of the page -- this is the URL you would use in a $.ajax()statement.

单击“测试”以执行 YQL 查询。一旦您对结果感到满意,请务必 (1) 单击“JSON”将响应格式设置为 JSON,以及 (2) 取消选中“诊断”以通过删除无关的诊断信息来最小化 JSON 负载的大小。最重要的一点是页面底部的 URL —— 这是您将在$.ajax()语句中使用的 URL 。

Here, I'm going to show you the exact steps to do a cross-domain form POST via a YQL query using this sample form:

在这里,我将向您展示使用此示例表单通过 YQL 查询执行跨域表单 POST 的确切步骤:

<form id="form-post" action="https://www.example.com/add/member" method="post">
  <input type="text" name="firstname">
  <input type="text" name="lastname">
  <button type="button" onclick="doSubmit()">Add Member</button>
</form>

Your JavaScript would look like this:

您的 JavaScript 将如下所示:

function doSubmit() {
  $.ajax({
    url: '//query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlpost%20where%0Aurl%3D%22' +
         encodeURIComponent($('#form-post').attr('action')) + '%22%20%0Aand%20postdata%3D%22' +
         encodeURIComponent($('#form-post').serialize()) +
         '%22%20and%20xpath%3D%22%2F%2F*%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=',
    dataType: 'json', /* Optional - jQuery autodetects this by default */
    success: function(response) {
      console.log(response);
    }
  });
}

The urlstring is the query URL copied from the YQL Console, except with the form's encoded actionURI and serialized input data dynamically inserted.

url字符串是从 YQL 控制台复制的查询 URL,除了表单的编码actionURI 和动态插入的序列化输入数据。

NOTE:Please be aware of security implications when passing sensitive information over the internet. Ensure the page you are submitting sensitive information from is secure (https:) and using TLS 1.x instead of SSL 3.0.

注意:通过 Internet 传递敏感信息时,请注意安全隐患。确保您提交敏感信息的页面是安全的 ( https:) 并使用 TLS 1.x 而不是 SSL 3.0

回答by user7420965

Here is the JSONP I wrote to share with everyone:

下面是我写的JSONP分享给大家:

the page to send req
http://c64.tw/r20/eqDiv/fr64.html

发送请求的页面
http://c64.tw/r20/eqDiv/fr64.html

please save the srec below to .html youself
c64.tw/r20/eqDiv/src/fr64.txt
the page to resp, please save the srec below to .jsp youself
c64.tw/r20/eqDiv/src/doFr64.txt

请将下面的srec保存到.html中
c64.tw/r20/eqDiv/src/fr64.txt
需要resp的页面,请将下面的srec保存到.jsp中
c64.tw/r20/eqDiv/src/doFr64.txt

or embedded the code in your page:

或在您的页面中嵌入代码:

function callbackForJsonp(resp) {

函数 callbackForJsonp(resp) {

var elemDivResp = $("#idForDivResp");
elemDivResp.empty();

try {

    elemDivResp.html($("#idForF1").val() + " + " + $("#idForF2").val() + "<br/>");
    elemDivResp.append(" = " + resp.ans + "<br/>");
    elemDivResp.append(" = " + resp.ans2 + "<br/>");

} catch (e) {

    alert("callbackForJsonp=" + e);

}

}

}

$(document).ready(function() {

$(document).ready(function() {

var testUrl = "http://c64.tw/r20/eqDiv/doFr64.jsp?callback=?";

$(document.body).prepend("post to " + testUrl + "<br/><br/>");

$("#idForBtnToGo").click(function() {

    $.ajax({

        url : testUrl,
        type : "POST",

        data : {
            f1 : $("#idForF1").val(),
            f2 : $("#idForF2").val(),
            op : "add"
        },

        dataType : "jsonp",
        crossDomain : true,
        //jsonpCallback : "callbackForJsonp",
        success : callbackForJsonp,

        //success : function(resp) {

        //console.log("Yes, you success");
        //callbackForJsonp(resp);

        //},

        error : function(XMLHttpRequest, status, err) {

            console.log(XMLHttpRequest.status + "\n" + err);
            //alert(XMLHttpRequest.status + "\n" + err);

        }

    });

});

});

});