weixin_33743248 2015-01-02 19:18 采纳率: 0%
浏览 34

打印$ .post响应

I have a simple web page with some option tags:

<!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>

Here's richiesta.php (called from the $.post function):

<?php

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

    $curl_parameters = array(
        'codicecomparto'    =>  trim($comparto),
        'codiceente'        =>  trim($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();

?>

Everything works fine. In Firebug I can see the request made from richiesta.php using the data gathered from POST is returned correctly.

enter image description here

I just can't find out how to print the response I see in Firebug on screen (or in the input tag).. I tried something like:

$('#data').change(function() {
    $.ajax({
      url: 'richiesta.php',
      type: 'POST',
      dataType: 'json',
      data: {value: this.value},
    }).done(function ( data ) {
      $('#textfield').val(data);
    });
});

The request still works but in #textfield I get [object Object], not the JSON.

  • 写回答

2条回答 默认 最新

  • weixin_33712881 2015-01-02 19:22
    关注

    As you have specified that the returned data is json (using dataType: 'json'), jQuery has already parsed it so it is not a string anymore, it is an object.

    If you want to see it as a json string in your #textfield, you would have to convert it to a string again:

    $('#textfield').val(JSON.stringify(data));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化