doujia4759 2012-06-15 09:51
浏览 88
已采纳

javascript将对象字符串转换为字符串

I cannot convert JS object to exact string, my code:

jsonObj['payment_value']=100.10;
jsonObj['payment_date']="2012-06-15";
jsonObjStr = JSON.stringify(jsonObj);
alert(jsonObjStr);
$.post("test", jsonObjStr.toString(), function(output){
    alert(output);
});

first alert displays:

{"payment_date":"2012-06-15","payment_value":100.1}

and in function test (i'm using codeigniter framework) it should print "payment_date" and "payment_value", code like this:

echo $this->input->post("payment_value");
echo $this->input->post("payment_date");

which is equvalent in "clear" php to:

echo $_POST["payment_value"];
echo $_POST["payment_date"];

but second alert displays clear string.

If I put

{"payment_date":"2012-06-15","payment_value":100.1}

instead of jsonObjStr.toString() it works fine

Does anyone knows how to fix it WITHOUT using json_decode? I need to have posted values in this format, not in other array

So i need to convert jsonObjStr exact to string (something inversely to function eval())

Thank in advice

  • 写回答

1条回答 默认 最新

  • duangu4943 2012-06-15 09:57
    关注

    According to $.post docs, second argument should be map or query string:

    map example:

    {
       "payment_date":"2012-06-15",
       "payment_value":100.1
    }
    

    query string example:

    'payment_date=2012-06-15&payment_value=100.1​​​'
    

    When you use JSON.stringify, then you get:

    '{"payment_date":"2012-06-15","payment_value":100.1}'
    

    which is invalid query string. So the solution is: do not stringify anything, pass the object itself as 2nd argument:

    jsonObj['payment_value']=100.10;
    jsonObj['payment_date']="2012-06-15";
    $.post("test", jsonObj, function(output){
       alert(output);
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看