【发布时间】:2020-02-28 06:59:54
【问题描述】:
WordPress 网站制作篮子。在那里,通过单击按钮,将 ajax 请求发送到服务器,处理通过 PHP。篮子存储 - 饼干。时序表明,当将数据从 js 传输到 PHP 时,主要制动恰好发生,反之亦然。 Js 和 PHP 本身工作正常。它将表单发送到 PHP。返回 - JSON 字符串。
我读过这个主题:
- https://wordpress.stackexchange.com/questions/315374/how-to-speed-up-admin-ajax-php-in-wordpress,
- https://wordpress.stackexchange.com/questions/41808/ajax-takes-10x-as-long-as-it-should-could,
- https://wp-kama.ru/id_3014/podgruzhaem-sredu-wordpress-s-minimalnoy-nagruzkoy-konstanta-shortinit.html。
但我已经准备好网站,但我害怕使用 SHARTIN ,因为我不知道其他 wp 功能会发生什么。 我尝试使用主题/my-theme/custom.php 而不是 admin-ajax.php,但它没有上下文。如果没有 COOKIEPATH,我的 cookie 将无法正常工作。
我想,也许我害怕 SHORTINT 是白白的?或者我在第二个变体中做错了什么?
我的代码:
function.php
add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){
wp_localize_script('main', 'myajax',
array(
'url' => admin_url('admin-ajax.php'),
'testurl' => get_home_url(null, 'wp-content/themes/my-theme/test.php')
)
);
}
main.js
$('.bars-addproduct').on('submit', function (e) {
e.preventDefault();
$form = $(this).serializeArray();
$.ajax({
url: myajax.testurl,
type: 'POST',
data: {
action: "addProduct",
form: $form,
},
success: function (res) {
console.log(res);
}
});
});
test.php
<?php
$name_cookie_basket = 'users_basket';
$cookies_time = time() + 60*24; //24min
$res = '';
$form = $_POST['form'];
foreach ($form as $field) {
switch ($field['name']) {
case 'productID':
$productID = $field['value'];
break;
case 'name':
$name = $field['value'];
break;
case 'price':
$price = $field['value'];
break;
case 'count':
$count = $field['value'];
break;
case 'amount':
$amount = $field['value'];
break;
case 'ownerID':
$ownerID = $field['value'];
break;
}
}
$cookie_basket = json_decode(stripslashes($_COOKIE[$name_cookie_basket]), true);
$products = $cookie_basket['products'];
$isModify = false;
$i = 0;
if (!$isModify) {
// если это не редактирование, а добавление
//Сначала проверим данные
if (((is_numeric($productID)) || ($productID == '')) &&
((is_numeric($price)) || ($price == '')) &&
((is_numeric($count)) || ($count == '')) &&
((is_numeric($amount)) || ($amount == '')) &&
((is_numeric($ownerID))) &&
((($amount != '') && (intval($amount) >= 0) && ($count == '')) || //это пополнение депозита
(($productID != '') && (intval($count) >= 0) && ($amount == ''))
)
){
//если все ок, добавляем
$newProduct = [
'productID' => $productID,
'name' => $name,
'price' => $price,
'count' => intval($count),
'amount' => intval($amount),
'ownerID' => $ownerID,
];
// add_row('bars_products', $newProduct, 'user_' . strval($current_user->ID));
array_push($products, $newProduct);
$res .= 'success added'."\n";
} else {
//если не ок
$res = 'fail';
}
}
$cookie_basket['products'] = $products;
$success = setcookie($name_cookie_basket, json_encode($cookie_basket), $cookies_time, '/');
if ($success) {
$res = json_encode([$products]);
} else {
$res = 'fail';
}
echo $res;
wp_die();
// }
【问题讨论】:
-
“我想,也许我害怕 SHORTINT 没什么?” - 我不知道你在这里甚至想问什么,抱歉。任何 SHORTINT(主要用作数据库数据类型的名称)与此有什么关系?