2016-09-27 142 views
0

我有这个变量$type,我希望它是monthyear。 应该通过按div进行更改。Ajax更改php变量

我试着用ajax调用创建一个onclick事件。

ajax呼叫和variable是在同一个脚本(index.php

内部的onclick功能:

var curr_class = $(this).attr('class'); 


$.ajax({ 
    type: "POST", 
    url: "index.php", 
    data: { 
     type: curr_class 
    }, 
    dataType: 'text', 
    success: function(data) { 
     // Test what is returned from the server 
     alert(data); 
    } 
}); 

但警告返回整个 HTML页面。 当我CONSOLE.LOG数据(创建var data = { type:curr_class }) and console.log *that data* it returns类型= month`(这是正确的)

,而我只是希望它返回个月

所以页面我顶可拨打

if(empty($_POST['type'])){ 
    $type = 'month'; 
} else { 
    $type = $_POST['type']; 
} 

并更改PHP变量,所以我可以在我的脚本的其余部分使用它。

但我怎么能ACC忘记这个?

随着亲切的问候,

+0

你不应该让一个Ajax请求你的'index.php',如果你不希望的'index.php'返回的内容。相反,编写一个单独的脚本来处理你的ajax请求。 – jeroen

+0

但是,如何更改* PHP变量*呢? @jeroen – EG47

+1

没有* PHP变量*这样的东西。每个变量只在脚本执行期间设置,在脚本完成后它不存在(除非使用会话,数据库等来存储信息)。 – jeroen

回答

0

为你发送请求到同一页面,从而导致整个页面是返回。你必须把它发送到另一个页面,从该页面返回变量类型

if(empty($_POST['type'])){ 
$type = 'month'; 
} else { 
    $type = $_POST['type']; 
    echo $type; 

保持在单独的文件中的代码,使一个AJAX调用该网页

+0

只使用jquery代码而不是php bcoz我们无法在php – ImBS

+0

中获得运行时变量值,以及如何*在代码的不同部分使用该变量? – EG47

+0

将其保存在会话可变数据库中 – Shahrukh

0
//Try This It's Work 
<a href="Javascript:void(0);" class="btn-my" data-title="month">Get Value</a> 
<a href="Javascript:void(0);" class="btn-my" data-title="year">Get Value</a> 
$(".btn-my").click(function(){ 
    var curr_class = $(this).data('title'); 
    $.ajax({ 
     type: "POST", 
     url: "index.php", 
     data: { 
      type: curr_class 
     }, 
     dataType: 'text', 
     success: function(data) { 
      // Test what is returned from the server 
      alert(data); 
     } 
    }); 
}); 
+0

返回整个html页面 – EG47

+0

现在您可以查看该代码 – ImBS

0

做,在这种方式

确保数据在DOM中可用。然后做下一步。

if(empty($_POST['type'])){ 
    $type = 'month'; 
    $monthOrDate = '<span id="date">'.$type.'</span>'; 
    echo $monthOrDate; 
} else { 
    $type = $_POST['type']; 
     $monthOrDate = '<span id="date">'.$type.'</span>'; 
    echo $monthOrDate; 
} 

然后在JavaScript中使用

$('#date').click(function(){ 
    alert($(this).val()); // if not then comment it use below one 
    alert($(this).text()); 
});