What's the best way to send JavaScript array to PHP script using GET?

前端 未结 6 642
轮回少年
轮回少年 2021-01-22 13:34

I have an interactive web application powered by jQuery where users can manipulate visual objects on the screen. When done, the \"state\" of JavaScript objects should be sent to

6条回答
  •  隐瞒了意图╮
    2021-01-22 13:57

    If it's just a simple flat array you don't need to do anything fancy, as PHP has a built in feature to parse array syntax from GET/POST variable names. Rough example below.

    Javascript side:

    // Do the parameter-building however you want, I picked the short/messy way
    var arrayvalues = [1, 2, 'a'];
    var querystring = "var[]=" + arrayvalues.join("&var[]=");
    querystring += "&var[something]=abcdef";
    // querystring is now "var[]=1&var[]=2&var[]=a&var[something]=abcdef"
    

    PHP side:

    var_dump($_POST);
    // Remember to validate the data properly!
    if ( is_array($_POST['var']) ) {
        count($_POST['var']);
        echo $_POST['var']['something'];
        array_map('do_something_interesting', $_POST['var']);
    }
    

提交回复
热议问题