Passing URL params with Jquery into php

2019-01-29 10:26发布

问题:

I'v been trying for last 2 hours to pass parameters from my jquery to PHP. I cannot seem to figure this out. So my code goes following

var something = getUrlParameter('month');
function Refresh()
{ 
$.ajax({

        type: 'POST',
        url: 'getCalendar.php',
        data: {test:something},
        success: function(data){
                 if(data != null) $("#calendarDiv").html(data)
         }
     });
}

getUrlParameter is

function getUrlParameter(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return sParameterName[1];
        }
    }
}​

I just cant seem to be able to pass anything to my php file. Thanks. My goal is to pass ?month=something&year=something into PHP file, so I can based on that display calendar.

Url of example: http://chanceity.com/calendartest.html

But it doesn't work because my php file is not getting those params.

回答1:

$.ajax({
    type: 'POST',
    url: 'getCalendar.php',
    cache: false,
    dataType:'json',
    data: "data=" + {test:something},
    success: function(data)
     {
         $("#calendarDiv").html(data)
     },
    error:function()
     {
        $("#calendarDiv").html('Could not get results')
     }
 });

and next go to your php file get the results and echo the variable back thats it

$value = htmlentities($_GET['data']);

if(!empty($value))
{
   $results = 'action you want to do ';
}
else
{
   $results = '';
}
echo json_encode($results);


回答2:

You can also do it with just javascript

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 
}