开发者

php array in url from json

Here is what I want to do:

I have some json like this

  var foo = {
   format:"json",
   type:"test",
   id:"26443"
  };

and I awant to put that in a url like this

 'http://example.com/a:3:{s:6:"format";s:4:"json";s:4:"type";s:4:"test";s:2:"id";s:5:"26443";}'

which I will then put into ajax call but everything I have tried results in error 501 BAD URI could someone tell me how to do this

I've tri开发者_如何学运维ed this EDIT:

after looking again and alerting the results of this function it IS build the results correcty they just arrn't being used propler either by ajax or the browser

 function js_array_to_php_array(a) {
  var a_php = "";
  var total = 3;

  for (var key in a){
   total;
   a_php = a_php + "s:" + String(key).length  + ":\""  + String(key) + "\";s:" + String(a[key]).length  +  ":\"" + String(a[key])  + "\";";
  }
  a_php = "a:" + total +":{" + a_php + "}";
  return a_php;
 }

when I use http fox it get this back

 http://example.com/a:3:%7Bs:6:%22format%22;s:4:%22json%22;s:4:%22type%22;s:4:%test%22;s:2:%22id%22;s:5:%2226443%22;}

which i find odd because it ecodes everything but the last curly bracket


Why not just use a "normal" query string?

http://example.com/?type=test&id=26443

$type = $_GET['type'];
$id   = $_GET['id'];

Unless I am missing something?


There is a jQuery function for this already! Use it and love it.

http://api.jquery.com/jQuery.param/


so as it turns out there is nothing wrong with the function js_array_to_php_array it did exactly as I needed it to the problem was that I needed to use JSONP instead of JSON when running my ajax call as I was going cross domain which also explains why the code worked in the url but not when I ran ajax

thank you all for your help


http://example.com/a:3:{s:6:"format";s:4:"json";s:4:"type";s:5:"test";s:2:"id";s:5:"26443";}

501 is right — that's not a valid URL. URLs definitely can't have quotes in them, or (for most part) curly brackets.

If you really have to submit a PHP literal structure in a URL without doing it as normal set of query parameters, you would have to URL-encode the invalid characters, which you can do like:

url= 'http://example.com/'+encodeURI(js_array_to_php_array(foo));

resulting in:

http://example.com/a:3:%7Bs:6:%22format%22;s:4:%22json%22;s:4:%22type%22;s:5:%22test%22;s:2:%22id%22;s:5:%2226443%22;%7D

incidentally this:

String(key)

is superfluous: object keys are always strings in JS, even if you put them in as numbers;

"\""  + String(a[key]) + "\""

is going to go wrong if the value can contain a quote or backslash, and

total;

there should surely be an increment here?


On the PHP end, you could use urlencode(json_encode($obj)) to convert an object to a string that can be used in a URL.

After I posted this, I realized you're trying to convert a JavaScript variable to a URL string after I saw var foo = {. Duh.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜