将POST请求发送到特定域?

时间:2012-06-23 16:08:48

标签: php javascript jquery ajax cross-domain

所以,我对网络开发还很陌生,而且我遇到了一些麻烦。我希望能够发送一个POST请求(或者真的,无论方法允许我这样做),从Firefox扩展/ Bookmarklet到我控制的PHP页面。

我一直在阅读跨源资源共享,但我还没有设法让它工作,我可以使用一些指导。

似乎jQuery ajax请求可以使这成为可能,但我还没有能够让它工作,也许是因为我是新手。

我最近一直在阅读这篇文章,而且我一直无法将它全部融合在一起,因为它似乎有很多正确的答案。

编辑:

所以我得到的PHP页面设置如下:

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: POST");

addLink($_POST['username'], $_POST['password'], $_POST['URL']);

该功能只是根据用户名/密码将URL添加到数据库中。这不是问题。

我已经使用来自同一域的请求:

$(document).ready(function() {
   $("a").click(function() {
      $.post("sendLinkInfo.php", { username: "<username here>", 
       password: "<password here>", URL: window.location.href },

   });
 });  

麻烦在于从任意bookmarklet / Firefox扩展跨域进行。

3 个答案:

答案 0 :(得分:1)

使用jQuery非常简单

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" },
  success: function(msg) {
      alert( "Data Saved: " + msg );
  }
});

答案 1 :(得分:1)

看一下jQuery文档:

var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
  url: "script.php", //Modify this part
  type: "POST",
  data: {id : menuId},
  dataType: "html"
});

request.done(function(msg) {
  $("#log").html( msg );
});

request.fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});

这应该跨域工作。

答案 2 :(得分:1)

对于跨域问题,您可以使用以下内容:

$("a").click(function() {
    $.ajax({
        type: 'POST',
        url: 'sendLinkInfo.php',
        crossDomain: true,
        data: {
            username: "<username here>",
            password: "<password here>",
            URL: window.location.href
        },
        dataType: 'html',
        success: function(data) {
           console.log(data);
        },
        error: function() {
            alert('POST failed.');
        }
    });
});
相关问题