dongmeixi5311 2015-05-25 16:48
浏览 85
已采纳

如何阻止jQuery ajax添加斜杠到JSON字符串?

I am sending stringified JSON object to a wordpress action

console.log( JSON.stringify(alloptions) );

$.ajax({
    type: "post",
    dataType: "json",
    url: ajaxurl,
    processData: false,
    data: {
        'action': 'create_preset',
        'preset': JSON.stringify(alloptions)
    },
    success: function( response ) {

        console.log( response );

    }
});

the console log of the stringified object before sent via ajax is this

http://prntscr.com/7990ro

so the string is correctly processed ,

but on the other side it comes out with slashes

function _create_preset(){

    if(!is_admin() && !isset($_POST['preset'])) return;

    print_r($_POST['preset']);

}

add_action("wp_ajax_create_preset", "_create_preset");

gives

{\"get_presets\":\"eedewd\",\"site_width\":\"1400px\",\"layout_type\":...

I know I can use

stripslashes( $_POST['preset'] )

to clean it up but that is what I am trying to avoid. I need the JSON string to be sent to the action as it is before the ajax, without slashes.

any help is appreciated!

and magic quotes is not on

http://prntscr.com/7996a9

*UPDATE AND SOLUTION

Jesse nailed it and WP was causing the trouble. Since the wp_unslash() is on its way to fix this in 5.0 https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/172 I added this to my code

global $wp_version;
$new_preset_options = $_POST['preset'];

if ( version_compare( $wp_version, '5.0', '<' ) ) {

    $new_preset_content = wp_unslash( $new_preset_options );

}else{

    $new_preset_content = $new_preset_options ;
}
  • 写回答

1条回答 默认 最新

  • douyu0845 2015-05-25 17:20
    关注

    WordPress made the decision a long time ago to auto add slashes to all global input variables ($_POST, etc). They pass it through an internal wp_slash() function. The official recommended way to remove these slashes is to use their provided wp_unslash:

    wp_unslash( $_POST['preset'] );
    

    Here is the codex reference.

    **Note: It looks like this might be getting fixed in version 5.0, where they will be doing the wp_unslash for you when you request values from the global input variables.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题