我正在使用此ajax调用发送和检索一些数据,并将结果保存在localstorage中,如下所示:
$.ajax({
url: "list.php",
data: {values: values},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}
});
然后我在一个单独的PHP文档中检索它并尝试将其添加到PHP变量中。我认为问题出现的原因是当我在console.log时,它会记录10次左右。我无法在PHP中回应它。我该如何正确传递?
<script>
var localData = JSON.parse(localStorage.getItem('key'));
$.each(localData, function(key, value){
console.log("This is the data that is stored", localData)
$.ajax({
type: 'post',
data: {localData},
dataType: "json",
success: function(result){
console.log(result)
}
});
</script>
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier = implode(", ", $user_id);
?>
答案 0 :(得分:2)
通过循环调用它会导致asynchronous functionality
ajax()真正的痛苦
为什么不使用join()
在js中加入", "
的项目,就像你在php中做的那样
<script>
var localData = JSON.parse(localStorage.getItem('key')).join(", ");
$.ajax({
type: 'post',
data: {localData},
dataType: "json",
success: function(result){
console.log(result)
}
});
</script>
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier = $user_id;
?>
如果 user_id需要是单个值且int
,您还应该将user
_ id强制转换为(int)
$verdier = (int) $user_id;