简体   繁体   English

如何将JavaScript数据发布到PHP?

[英]How to post javascript data to PHP?

If I have a variable that needs to be posted to a PHP script without refreshing the page. 如果我有一个需要在不刷新页面的情况下将其发布到PHP脚本的变量。 Is this possible? 这可能吗? And if so, how? 如果是这样,怎么办?

My attempt using jQuery: 我尝试使用jQuery:

$.ajax({
   url: "myphpfile.php",
   type: "post",
     data: json/array/whatever,

     success: function(){ // trigger when request was successfull
       window.location.href = 'somewhere'
     }
   })

How would I receive an array passed in my php script? 我将如何接收通过PHP脚本传递的数组?

Use GM_xmlhttpRequest() to allow for cross-domain posts (which it will be in most scenarios). 使用GM_xmlhttpRequest()允许跨域发布(在大多数情况下都是如此)。

Greasemonkey Script: Greasemonkey脚本:

// ==UserScript==
// @name     _Sending arbitrary data, demo
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    GM_xmlhttpRequest
// ==/UserScript==

var someArray       = [1, 2, 3];
var serializedData  = JSON.stringify (someArray);

GM_xmlhttpRequest ( {
    method:     "POST",
    url:        "http://SERVER.COM/PATH/ShowJSON_PostedData.php",
    data:       serializedData,
    headers:    {"Content-Type": "application/json"},
    onload:     function (response) {
                    console.log (response.responseText);
                }
} );


ShowJSON_PostedData.php: ShowJSON_PostedData.php:

<?php
    echo '<title>JSON data</title>';

    echo '<h2>JSON post data:</h2><pre>';

    $jsonData   = json_decode($HTTP_RAW_POST_DATA);
    print_r ($jsonData);

    echo '</pre>';
?>


The console. 控制台。 will show: 将会呈现:

<title>JSON data</title><h2>JSON post data:</h2><pre>Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
</pre>

The accepted answer of this thread may be really useful since it shows a simple case : using jquery $.ajax to call a PHP function 该线程的可接受答案可能非常有用,因为它显示了一个简单的情况: 使用jquery $ .ajax调用PHP函数

My suggestion is : make something that works, then progressively add complexity until you reach your custom case. 我的建议是:先做一些有用的事情,然后逐步增加复杂性,直到达到您的自定义案例为止。 This way you feel much safer and you are aware of potential problems as they get in. 这样,您会感到更加安全,并且可以在潜在问题出现时意识到这些问题。

To pass an array from php to the client side, you may use echo json_encode($myArray); 要将数组从php传递到客户端,可以使用echo json_encode($myArray); in your php script. 在您的PHP脚本中。

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM