简体   繁体   English

Ajax将javascript变量发送到php

[英]Ajax to send javascript variable to php

I'm trying to send a javascript string variable from a javascript plugin of a program running in tomcat, to a php file hosted on apache (httpd on centOS) on the same physical machine. 我正在尝试将tomcat中运行的程序的javascript插件中的javascript字符串变量发送到同一物理机上apache(centOS上的httpd)上托管的php文件。

Trying to send it using ajax and POST, and storing it as a variable on the php file. 尝试使用ajax和POST发送它,并将其作为变量存储在php文件中。

I'm new to php 我是php新手

php: PHP:

<?php

    if($_POST['zone']){
        $zone=($_POST['zone']);
        echo $zone;
    }
?>

ajax call: ajax呼叫:

$.ajax({
    type: 'POST',
    url: 'urlofmyfile.php',//url of receiver file 
    data: {zone: zone}, //your data
    success: function(msg){console.log('Write succeeded' + msg);}, //callback when ajax request finishes
    dataType: 'jsonp' //text/json...
});

I initially got some errors about cross domain problems, then switch to jsonp as the dataType 我最初遇到一些有关跨域问题的错误,然后切换为jsonp作为dataType

I use $.post for this kind of request and use json output in PHP for better communication with JQuery. 我将$ .post用于这种请求,并在PHP中使用json输出以更好地与JQuery进行通信。 One more thing, you also need to check whether the value of zone is not empty or what! 还有一件事,您还需要检查zone的值是否为空或什么!

in PHP Code 用PHP代码

<?php
$output = array('status'=>true,'message'=>'');
if(!empty($_POST['zone']) && $_POST['zone']){
    $zone=($_POST['zone']);
    $output['status'] = 'true';
    $output['message'] = $_POST['zone'];
}
else
{
    $output['status'] = 'false';
    $output['message'] = 'No value passed';
}
header('Content-Type:application/json;');
echo json_encode($output);

This will help to check better operation of PHP script via javascript 这将有助于通过javascript检查PHP脚本的更好操作

in Javascript 用Java语言编写

$.post(urlofmyfile.php,
{
 zone: zone
},
  {
  function(data,status){
    if(data['status']=='true'){
        //It's Done
    }
    else
    {
       //it's not done
    }
  }
}
);

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

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