xmlhttprequest中的复选框数组以及其他数据

时间:2016-10-10 19:25:32

标签: javascript php html arrays checkbox

如果这是一个重复问题,我很抱歉,但我搜索并搜索过,似乎无法找到任何答案。我将要解决这个问题......

我正在使用REST API / JSON制作一个Web服务表单,并且除了一系列复选框之外,还有一切正在进行中。如果值进入xmlhttp打开请求,则在数组周围有双引号{checkboxvar:“[”Option One“,”Option 2“]”},将其转换为字符串。它抛出一个转换字符串错误b / c API期望一个数组。

我很失落如何做到这一点..非常感谢能帮助我的人!

我有一个带有一些复选框的HTML表单:

... yada yada yada ....   

<div id="multipleSelect">
        <input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
        <input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
        <input type='checkbox' name='checkboxvar[]' value='Option Three'>3
   </div>

    ... yada yada yada ....

<button id="createSubmit" onclick="createContact()">Create</button>

使用链接到此Javascript功能的按钮:

function createContact(){

  if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            var response = JSON.parse(xmlhttp.responseText);
            if(response['status'] == "ok")
            {
        $('#createContact').fadeOut(800);
            }
            else if(response['status'] == "error")
            {
                alert(response['message']);
            }
            else
            {
                alert("Something REALLY went wrong. And to be honest I don't know what yet.");
            }
        }
    };

      xmlhttp.open("GET", "php/create.php?module=Contacts&data=First%20Name:" 
      + document.getElementById('first_name').value +
      "|Middle%20Name:" + document.getElementById('middle_name').value +
      "|Last%20Name:" + document.getElementById('last_name').value, true);
      xmlhttp.send();
    }

然后将请求发送到此PHP文件:

<?php

$module = $_GET['module'];
$dataurl = urldecode($_GET['data']);
$fields = explode("|",$dataurl);
$data = array();

for($i=0;$i<sizeof($fields);$i++)
{
    $field = explode(":",$fields[$i]);
    $data[$field[0]]=$field[1];
}
$data = '{"createFields": '.json_encode($data).',"returnFields":["Entity ID"]}';

if($module)
{
    $call   = $host."modules/".$module."/";
}
else
{
    $call   = $host."modules/"."noModule"."/";
}

echo $data;
$curl = curl_init($call);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Connection: Keep-Alive'));
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($curl, CURLOPT_USERPWD, $userName.":".$passKey);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
echo $curl_response;
        ?>

0 个答案:

没有答案