【问题标题】:How split comma in AJAX data如何在 AJAX 数据中拆分逗号
【发布时间】:2022-12-31 23:07:31
【问题描述】:

如果复选框被选中或未选中,我使用此脚本发送:

<script>
    $(document).ready(function() {
  $('.model').click(function() {
    var formData = $('#myForm').serialize();
    console.log('Posting the following: ', formData);
    
 // send ajax
 $.ajax({
                url: 'av_check.php', // url where to submit the request
                type : "POST", // type of action POST || GET
                dataType : 'json', // data type
                data : $("#myForm").serializeArray(), // post data || get data
                success : function(result, status, xhr) {
                  

                    alert("response was "+result);
                    // you can see the result from the console
                    // tab of the developer tools
                    console.log(result);

                },
                error: function(xhr, resp, text) {
                    console.log(xhr, resp, text);
                }
            
            })
        });
    });

</script>

这是我的复选框:

<input id="model" name="model[]" class="model" type="checkbox" value="VARIABLE">

还有我的 PHP:

echo json_encode($_POST['model']);

当检查多个复选框时,我得到:

回应是

08:15,08:30,08:45

(复选框的值是不同的时间)

到目前为止一切顺利,但我想在 PHP 页面上处理这些数据。 所以我尝试$str_arr = explode (",", $_POST['model']);拆分值,但它似乎不起作用。

所以我搜索了如何处理这些数据,但我似乎无法找到它。也许我没有使用正确的术语,但是有人知道如何处理这些数据吗?

【问题讨论】:

  • 看起来 $_POST['model'] 是一个值数组,因此您可以使用类似 foreach($_POST['model'] as $model) 的内容
  • 你为什么不发送formData(你已经使用serialize()序列化了,而不是再次序列化表单,但那次使用serializeArray()?你的意思也不清楚“它似乎不起作用”.什么时候?在哪里?如何?

标签: php jquery ajax


【解决方案1】:

json_encode 是将字符串编码为json,但是你的字符串已经是json格式了。我认为您只需要改用 json_decode 即可。

将其作为对象返回:

$checkBoxObject = json_decode($_POST['model']);

将其作为数组返回

$checkBoxArray = json_encode($_POST['model'], true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 2019-10-13
    相关资源
    最近更新 更多