【发布时间】:2018-06-13 08:16:54
【问题描述】:
我已经把头发扯了 2 天,试图解决这个问题,我想知道你们中的任何人是否可以提供帮助?我正在尝试将 XML 字符串发布到服务器,并且他们声明“所有 XML 请求都应使用 HTTP POST 方法以“xml”参数名称发送到我们的服务器”。我已经尝试了很多方法,但没有任何乐趣(如果我使用带有表单的 javascript,它可以正常工作,但这对项目不实用)。请有人能指出我正确的方向吗?我将首先在下面发布我无法工作的 PHP/CURL 代码,然后是可以正常工作的 Javascript 代码。我想我只是想在 PHP/CURL 代码中模拟 Javascript
PHP/CURL 代码
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<Request>
<Head>
<Username>username</Username>
<Password>password</Password>
<RequestType>GetCities</RequestType>
</Head>
<Body>
<CountryCode>MX</CountryCode>
</Body>
</Request>';
$url = "http://example.com";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
echo $output;
curl_close($ch);
Javacript 代码(有效)
function submitForm() {
var reqXML = "<Request><Head><Username>username</Username> <Password>password</Password><RequestType>GetCities</RequestType></Head><Body><CountryCode>MX</CountryCode></Body></Request>";
document.getElementById("xml-request").value = reqXML;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("xml-response").value = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "http://example.com", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("xml=" + reqXML);
return false;
【问题讨论】: