如何使用ajax和php

时间:2016-08-23 19:09:19

标签: javascript php ajax

我尝试使用AJAX(纯JS)将数据发送到服务器。我想在请求机构发送它。

我知道如何在jQuery中执行此操作:

$.ajax({
    url: 'someurl',
    data: 'foo'
});

我的意思是如何在纯js中使用带有数据属性的ajax方法时,如jQuery所能将数据发送到服务器?

另外,在PHP中,我该如何获取这些数据?

我知道,我需要做laravel

Request::getContent();

(如果我没记错的话)

但我不知道如何用PHP获取这些数据。

由于

2 个答案:

答案 0 :(得分:2)

在通过javascript发送AJAX请求而不依赖于jQuery方面,这是一个非常广泛的问题。你应该review the documentation here

一个简单的例子

// Old compatibility code, no longer needed.
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data = /* some data here */
httpRequest.send('data=' + encodeURIComponent(data));

要在PHP中检索此项,您可以使用$_POSTfile_get_contents('php://input'),具体取决于请求中发送的Content-type标头。在上面的示例中,我们使用带有application/x-www-form-urlencoded HTTP谓词的Content-type POST标头,因此信息将填充在$_POST['data']中。

答案 1 :(得分:-1)

希望这有帮助!这是一个范围很广的AJAX请求,我试图让这个例子尽可能简单易懂! :)

我的Web-page.php文件

<a onclick="<?php $myValue; ?>">Send request</a>

<script>
    $.ajax({
        type: "POST",
        url: 'my-script.php',
        data:{
            action: 'send',
            key: $myValue
        }
    });
</script>

我-的script.php

<?php
    $myValue = $_POST['key'];
?>