dpa55065 2013-06-29 18:42
浏览 91

将php curl更改为json响应

currently I have a php file that returns the data to the client via curl, I have changed the client to respond to JSON, to handle a problem and all works great. But now is it possible to return the data as JSON object. It currently Returns alot of html tags etc that I am not interested in,I would like to return just the raw text as an example the text is in this format C5:3;

Below is the code would appreciate if anyone could point me in the right direction.

//set POST variables
  $url = $_POST['url'];
  unset($_POST['url']);
  $fields_string = "";
  //url-ify the data for the POST
  foreach($_POST as $key=>$value) {
   $fields_string .= $key.'='.urlencode($value).'&';
   }
  rtrim($fields_string,"&");
   //open connection
   $ch = curl_init();
   //set the url, number of POST vars, POST data
   $url .= '&';
   $url .= $fields_string;
   curl_setopt($ch,CURLOPT_URL,$url);
   //execute post

   $string = curl_exec($ch);

   curl_close($ch);

I am looking to return a JSON object like this,

$data = array('success'=> true,'message'=>'C5;3');

This is the client code.

     $("button.checkStatus").click(function(){
            //This Ajax checks the current on/off status of the passed X10 code            
            $('img.checkStatus').each(function(i, obj) {
                var element = $(this);
                $x10Device = $(this).data("x10");
                var postData = "url=http://192.168.0.34:81/tenHsServer/tenHsServer.aspx?t=ab&f=DeviceStatus&d=" + $x10Device ; 



 $.ajax({
    type: "POST",
    dataType: "json",
    data: postData,
    beforeSend: function(x) {
        if(x && x.overrideMimeType) {
            x.overrideMimeType("application/json;charset=UTF-8");
        }
    },
    url: 'urlencodeJson.php',
    success: function(data) {
        // 'data' is a JSON object which we can access directly.
        if (data.success == true){
            $('#section1').html(data.message);
            //$("x10").data('src','lightbulbon.png');
             element.attr('src','lightbulbon.png');
    }
        else{
            $('#section2').html(data.message);     
             element.attr('src','lightbulbon.png');
        }
    }
   });
  • 写回答

2条回答 默认 最新

  • dongzai5181 2013-06-29 18:47
    关注
    <?php
    header("Content-Type: text/plain"); //if html elements exists in array, it will echo as plain text
    
    $yourarray = array('success'=> true,'message'=>'C5;3');
    
    echo json_encode($yourarray);
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么