使用列表函数(?)无法正确传递变量

时间:2015-01-01 18:49:06

标签: php post curl explode

这是一个片段,我使用从指定2个变量的URL收集JSON中的一些数据:

<?php

function soldipubblici() {

    $curl_parameters = array(
        'codicecomparto'    =>  "PRO",
        'codiceente'        =>  "011120674",
    );

    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,"http://soldipubblici.gov.it/it/ricerca");
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query( $curl_parameters ));
    curl_setopt($ch,CURLOPT_HTTPHEADER,array (
        "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
        "Accept: application/json",
        "X-Requested-With: XMLHttpRequest",
    ));

    $output=curl_exec($ch);

    curl_close($ch);
}

echo soldipubblici();

?>

您可以注意到变量是手动设置的。所以我提出了一个包含2个选项的简单网页。输入标记仅用于测试POST数据。

<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<form>
<label>Seleziona l'ente</label>
<select name="data" id="data">
    <option value="PRO - 011142764">COMUNE DI AGLIE'</option>
    <option value="PRO - 011120674">COMUNE DI AGRATE CONTURBIA</option>
</select>
<input type="text" name="textfield" id="textfield" />
</form>

<script>
$('#data').change(function() {
    $.post("richiesta.php", { value: this.value });
    $('#textfield').val(this.value);
});
</script>
</body>
</html>

这是richiesta.php,它接收有关更改事件的POST数据(我跟着this线程):

<?php
list($comparto, $ente) = explode("-", $_POST['value'], 2);
echo "comparto: $comparto, ente: $ente";
?>

请求正常,在更改事件时我成功获取POST值:

enter image description here

因为它有效,我现在可以放在richiesta.php我的&#34;真实&#34;函数有两个变量,这次不是手动但是从POST请求中检索值:

<?php

function soldipubblici() {
    list($comparto, $ente) = explode("-", $_POST['value'], 2);

    $curl_parameters = array(
        'codicecomparto'    =>  $comparto,
        'codiceente'        =>  $ente,
    );

    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,"http://soldipubblici.gov.it/it/ricerca");
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query( $curl_parameters ));
    curl_setopt($ch,CURLOPT_HTTPHEADER,array (
        "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
        "Accept: application/json",
        "X-Requested-With: XMLHttpRequest",
    ));

    $output=curl_exec($ch);

    curl_close($ch);
}

echo soldipubblici();

?>

不幸的是它不起作用:( 我在Firebug中得到一个空的响应...如果在相同的片段中我手动设置2个变量,如果有效......看起来他们没有从list函数正确传递。

1 个答案:

答案 0 :(得分:0)

选项中的-周围有空格,您可能需要删除它们。

$curl_parameters = array(
    'codicecomparto' => trim($comparto),
    'codiceente' => trim($ente),
);