我正在使用 PHP 解析来自最终用户的 XML,然后将其传递给 Javascript 函数进行处理。我只需要一些值是必需的,其余的值是可选的。我尝试将值设置为空字符串,但传递空变量时出现错误。
我怎样才能解决这个问题?
<script type="text/javascript">
function CreateDevice(id, type, name, datacenter, os, whmcsid, ipmihost, ipmiuser, ipmipass, remotehost, remoteuser, remotepass)
{
$.ajax({
type: "POST",
url: "handler.php",
data: { 'action_type': 'create_device',
device_id: id,
device_type: type,
device_name: name,
datacenter: datacenter,
operating_system: os,
whmcs_id: whmcsid,
ipmi_host: ipmihost,
ipmi_user: ipmiuser,
ipmi_pass: ipmipass,
remote_host: remotehost,
remote_user: remoteuser,
remote_pass: remotepass},
dataType: 'json',
success: function(data)
{
alert("SUCCESS!");
}
});
}
<?
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (empty($_POST["device_xml"]))
{
echo 'No Data Posted';
exit;
}
$device_xml = $_POST["device_xml"];
$devices = simplexml_load_string($device_xml);
foreach ($devices->device as $device)
{
$device_id = $device->id;
$device_name = $device->name;
$device_type = $device->type;
$datacenter = $device->datacenter;
$os = $device->os;
$whmcs = $device->whmcs;
$ipmihost = $device->ipmihost;
$ipmiuser = $device->ipmiuser;
$ipmipass = $device->ipmipass;
$remotehost = $device->remotehost;
$remoteuser = $device->remoteuser;
$remotepass = $device->remotepass;
if ($device_id == "") { echo "Error: Device ID Must be Specified"; exit; }
if ($device_name == "") { echo "Error: Device Name Must be Specified"; exit; }
if ($device_type == "") { echo "Error: Device Type Must be Specified"; exit; }
if ($datacenter == "") { echo "Error: Datacenter Must be Specified"; exit; }
if (!$os) { $os = ""; }
if (!$whmcs) { $whmcs = ""; }
if (!$ipmihost) { $ipmihost = ""; }
if (!$ipmiuser) { $ipmiuser = ""; }
if (!$ipmipass) { $ipmipass = ""; }
if (!$remotehost) { $remotehost = ""; }
if (!$remoteuser) { $remoteuser = ""; }
if (!$remotepass) { $remotepass = ""; }
echo "CreateDevice(" . $device_id . "," . $device_name . "," . $device_type . "," . $datacenter . "," . $os . "," . $whmcs . "," .
$ipmihost . "," . $ipmiuser . "," . $ipmipass . "," . $remotehost . "," . $remoteuser . "," . $remotepass . ");";
}
}
?>
</script>