js对象通过ajax发送

huangapple go评论64阅读模式
英文:

js object sending through ajax

问题

我花了两天时间试图解决这个问题,但无法解决。

我通过jQuery AJAX将存储在浏览器中的会话发送到PHP函数,以便将数据保存到WordPress数据库中。

在会话存储中,数据存储如下 -

所以这个没有成功:

var dataStorage = JSON.stringify(sessionStorage.getItem('shoppingCart'));

$.ajax({
    url: "https://mywebsite.com/wp-admin/admin-ajax.php",
    method: "POST",
    data: 'globalvar='+dataStorage+'&action=myfunction',
    dataType: "json"  
}).done(function (response) {});

PHP函数是:

if (!function_exists('myfunction')) {

    function myfunction() {

        $object = $_POST['globalvar'];

        $decoded_object = json_decode($object);

        //wordpress更新数据库                 
        update_post_meta('42393', 'menu_items_list',  $menu_make_arr);

    }

    add_action('wp_ajax_myfunction', 'myfunction');
    add_action('wp_ajax_nopriv_myfunction',  'myfunction');
}

我在数据库中得到了null,像这样。

英文:

I have spent two days trying to get the issue resolved, but can't get it done.

I am sending session stored in browser through jQuery AJAX to PHP function so that to save the data to WordPress db.

in session Storage data is stored like this -

js对象通过ajax发送

so this without success:

var dataStorage = JSON.stringify(sessionStorage.getItem('shoppingCart'));


       $.ajax({
            url: "https://mywebsite.com/wp-admin/admin-ajax.php",
            method: "POST",
            data: 'globalvar='+dataStorage+'&action=myfunction',
             dataType: "json"  
        }).done(function (response) {});

the PHP function is:

if (!function_exists('myfunction')) {

function myfunction() {
    

     
  $object = $_POST['globalvar'];
     
     $decoded_object = json_decode($object);

       //wordpress update db                 
      update_post_meta('42393', 'menu_items_list',  $menu_make_arr);
        
 }

     
             add_action('wp_ajax_myfunction', 'myfunction');
            add_action('wp_ajax_nopriv_myfunction',  'myfunction');
}

I get null in db like this

js对象通过ajax发送

答案1

得分: 1

首先,sessionStorage已经存储了一个字符串,而你保存的变量不应该叫做sessionStorage,因为它会隐藏原始sessionStorage的名称。同时,尽量避免使用"var",而是使用const和let。

const shoppingCart = sessionStorage.getItem('shoppingCart')

其次,你正在将数据URL编码到HTTP请求的主体中(而且JSON部分可能会混淆)。

encodeURIComponent(shoppingCart)

我的建议是将所有内容都编码成JSON。因为你已经使用了"dataType: 'json'"来提供协议(实际数据为application/x-www-form-urlencoded而不是application/json)。

JavaScript:

const shoppingCart = JSON.parse(sessionStorage.getItem('shoppingCart'))

$.ajax({
  url: "https://mywebsite.com/wp-admin/admin-ajax.php",
  method: "POST",
  data: JSON.stringify({
    globalvar: shoppingCart,
    action: "myfunction"
  }),
  dataType: "json"  
}).done((res) => {});

PHP:

$json = file_get_contents('php://input');
$body = json_decode($json);

$func = $body->action;
$data = $body->globalvar;
英文:

Firstly, the sessionStorage already stores a string, and the var you are saving into, shouldn't be called sessionStorage, because it hides the name of the original sessionStorage. Also avoid using "var" alltogether, use const and let.

const shoppingCart = sessionStorage.getItem('shoppingCart')

Secondly, the data you are sending is URL encoded into the body of the HTTP request (and the JSON part probably gets scewed up).

encodeURIComponent(shoppingCart)

My recommendation would be to encode everything in JSON. Since you are already "lying to the protocol" with the dataType: "json" you provided (your actual data is application/x-www-form-urlencoded not application/json).

JS:

const shoppingCart = JSON.parse(sessionStorage.getItem('shoppingCart'))

$.ajax({
  url: "https://mywebsite.com/wp-admin/admin-ajax.php",
  method: "POST",
  data: JSON.stringify({
    globalvar: shoppingCart,
    action: "myfunction"
  }),
  dataType: "json"  
}).done((res) => {});

PHP (🤢):

$json = file_get_contents('php://input');
$body = json_decode($json);

$func = $body->action;
$data = $body->globalvar;

答案2

得分: 1

要在PHP中读取`application/json`,我们可以使用`php://input`

所以代码会像这样:
```php
function myfunction() {
        $rawData = file_get_contents("php://input");
        $json = json_decode($rawData);

        $object = $json->globalvar;

要从浏览器发送application/json到PHP,我们可以使用JSON.stringify

所以代码会像这样:

sessionStorage.setItem("shoppingCart", JSON.stringify([{"name": "name1"},{"name": "name2"}]));

var dataStorage = JSON.parse(sessionStorage.getItem('shoppingCart'));

$.ajax({
	url: "test1.php",
	method: "POST",
	data: JSON.stringify({ "globalvar": dataStorage, "action" : "myfunction"}),
	dataType: "json"  
}).done(function (response) {
	console.log(response)
});
英文:

To read application/json in php we can use php://input

So the code will be like this

function myfunction() {
        $rawData = file_get_contents("php://input");
        $json = json_decode($rawData);

        $object = $json->globalvar;

To send application/json from browse to php we can use JSON.stringify

So the code will be like this

sessionStorage.setItem("shoppingCart", JSON.stringify([{"name": "name1"},{"name": "name2"}]));

var dataStorage = JSON.parse(sessionStorage.getItem('shoppingCart'));

$.ajax({
	url: "test1.php",
	method: "POST",
	data: JSON.stringify({ "globalvar": dataStorage, "action" : "myfunction"}),
	dataType: "json"  
}).done(function (response) {
	console.log(response)
});

答案3

得分: 0

I think sessionStorage is a reserved keyword so it is creating the issue. You can debug the variable state. This code works for me.

var dataStorage = JSON.stringify(sessionStorage.getItem('shoppingCart'));

$.post({
  url: "https://mywebsite.com/wp-admin/admin-ajax.php",
  method: "POST",
  data: 'globalvar=' + encodeURIComponent(dataStorage) + '&action=myfunction',
  dataType: "json"
}).done(function(response) {});

PHP Code - Just removed a few lines for debugging

if (!function_exists('myfunction')) {
    
    function myfunction()
    {
        $object = $_POST['globalvar'];
        $decoded_object = json_decode($object);
        print_r($decoded_object);
    }

    myfunction();
}
英文:

I think sessionStorage is a reserved keyword so it is creating the issue. You can debug the variable state. This code works for me.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var dataStorage = JSON.stringify(sessionStorage.getItem(&#39;shoppingCart&#39;));

$.post({
  url: &quot;https://mywebsite.com/wp-admin/admin-ajax.php&quot;,
  method: &quot;POST&quot;,
  data: &#39;globalvar=&#39; + encodeURIComponent(dataStorage) + &#39;&amp;action=myfunction&#39;,
  dataType: &quot;json&quot;
}).done(function(response) {});

<!-- end snippet -->

PHP Code - Just removed a few lines for debugging

if (!function_exists(&#39;myfunction&#39;)) {

    function myfunction()
    {
        $object = $_POST[&#39;globalvar&#39;];
        $decoded_object = json_decode($object);
        print_r($decoded_object);
    }

    myfunction();
}

答案4

得分: 0

以下是翻译好的部分:

1. Is the function defined as you want?

Your

if (!function_exists('myfunction')) {
    //...
}

检查 myfunction 是否存在,仅在尚未存在此名称的函数时才执行内部代码块。您需要确保您的函数最终存在,并且一些旧的同名函数不会阻止创建此函数。

2. Is your JSON in proper format?

您正在对会话数据进行 json_decode,在数据库级别,您需要存储像这样的值

'[{"name":"том","price":259,"count":1},{"name":"жак","price":299,"count":1}]'

在您记录中。请确保您存储 JSON 的方式在 WordPress 中是有效的。

3. Check the Network tab of your Dev Tools

您需要确保您的请求被正确发送,并且您期望发送的 JSON 在所有操作之后都被发送。

4. Make sure myfunction is being executed after all

为了确保这个函数被执行,最好添加一些日志记录以查看它是否被执行。

英文:

There are several aspects to fix/check:

1. Is the function defined as you want?

Your

if (!function_exists(&#39;myfunction&#39;)) {
    //...
}

Checks whether myfunction exists and only executes he inner block if a function by this name does not already exist. You will need to make sure that your function ends up existing and some older function by the same name does not prevent this function from being created.

2. Is your JSON in proper format?

You are json_decode'ing your session data and on the database level you would need to store a value like

&#39;[{&quot;name&quot;:&quot;том&quot;,&quot;price&quot;:259,&quot;count&quot;:1},{&quot;name&quot;:&quot;жак&quot;,&quot;price&quot;:299,&quot;count&quot;:1}]&#39;

into your record. Try to make sure that the way you are storing your JSON is valid in WordPress.

3. Check the Network tab of your Dev Tools

You will need to make sure that your request is being sent properly and the JSON you expect to be sent is being sent after all.

4. Make sure myfunction is being executed after all

It would not hurt to add some logging to this function to see that it's being executed.

huangapple
  • 本文由 发表于 2023年1月8日 22:39:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定