Passing multiple arguments through HTTP GET

I have an HTML file referencing a PHP script to perform various functions. One of the ways the HTML file calls the PHP script is through an HTTP GET. The GET request should pass three parameters and return a list of all saved events as a JSON-encoded response.

So far, I have the following but I'm not sure how to pass the three arguments through the HTTP GET. Also, I'm not sure if I am returning the JSON-encoded response correctly:

  if($_SERVER['REQUEST_METHOD'] == 'GET'){
        echo json_encode(events.json); }

GET requests are done through the URL... So if you want to pass three GET requests you would do...

http://www.domain.com/target.php?param1=whatever&param2=whatever&param3=whatever

target.php represents the PHP script file you want to send the information to. You can have as many variables as you want but just keep in mind that every other GET request has to be separated by an & symbol. The first param simply has to be started off with a ? symbol.

If you want to use Javascript, I would recommend using JQuery. You can do something like this

$.get('target.php?param1='+whatever+'&param2='+whatever2, function(data) {
    alert(data);
});

Or you can use window.location to send a link with the appropriate link above.

If you want to use AJAX specifically, here is a way of doing it with JQuery (there are ways with Javascript that I could update later if necessary:

 $.ajax({
  type: "GET",
  url: "http://www.domain.com/target.php",
  data: { param1 : "whatever", param2 : "whatever", param3 : "whatever" }, 
  success: function(result){
       //do something with result
       }
  })

If you want to access the variables, you can call $_GET['param1'] or $_REQUEST['param1'] to get access to them in PHP. Simply change the name in the brackets to the desired variable you want and store it in a variable.

If you want to access the params with Javascript... well the most efficient way is to go and decode the URL that was used and pull them out. See here

Hope this helps!


You can access the parameters from the URL via the $_GET superglobal in PHP.

For example, if your URL is http://example.com/test.php?param1=foo&param2=bar , then you could access them in PHP like so:

 $param1 = $_GET['param1'];
 $param2 = $_GET['param2'];

See http://www.php.net/manual/en/reserved.variables.get.php for more details.

As for returning a valid JSON response, you can check out this answer. It uses PHP's header function.

链接地址: http://www.djcxy.com/p/45826.html

上一篇: PHP会回应错误的原因,即使有错误

下一篇: 通过HTTP GET传递多个参数