简体   繁体   English

将javascript值传递给php变量

[英]transferring a javascript value to a php variable

将以下输出值转换为php变量的最佳方法是什么?

$(document).getUrlParam("id");

Through an ajax post. 通过ajax帖子。

$.ajax({
 type: 'POST',
 url: url,
 data: data,
 success: success,
 dataType: dataType
});

You should use JSON format to send and receive data from javascript to PHP. 您应该使用JSON格式从javascript发送和接收数据到PHP。 For example 例如

 function sendData(){

  //with jquery, you can use `.post()`, `.get()` or for more control `.ajax()`
  $.post(
      //URL to send the data
       url,
      //data being sent, transformed to JSON
      {dataSent: JSON.stringify(clientSideData)},
      //Do something after sendind the data to server
      function(dataReceived){
         //transform data from json format to javascript object
         var dataLog = jQuery.parseJSON(dataReceived);

         //Do stuff

      }
   )
  }

PHP: PHP:

 //Receive data from POST
 var phpVar = json_decode($_POST['dataSent'])

 //send data back to javascript
 echo json_encode(phpVar)

While all of these answers will get the value from javascript into the PHP script, I'd wonder if you need javascript at all. 虽然所有这些答案都会从javascript中获取PHP脚本的价值,但我想知道你是否需要javascript。

From what I can see from a brief google the getUrlParam plugin is useful for getting and then breaking down the URL. 从我在简短的谷歌中可以看到,getUrlParam插件对于获取然后分解URL非常有用。 Have you had a look at the variables available through $_SERVER ? 您是否看过$ _SERVER提供的变量? I'm sure you'd be able to find something suitable in there. 我相信你能找到合适的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM