如何在同一页面上将ajax val传递给php变量?

问题描述:

$('#test-test_id').change(function() { 
     var myValue = $(this).val(); 
    }); 

// $getMyValue = $(this).val(); 

例如,通过使用上面的代码,我想通过$(this).val到同一页面上的php变量。这怎么可能?如何在同一页面上将ajax val传递给php变量?

+1

使一个XMLHttpRequest或使用表格并提交 – Ghost

+0

同意@Ghost。用参数调用本身会使AJAX在这里无用。 – noob

windown.location可以用参数重新加载页面。您可以尝试在发送VAL像下面PHP变量...

<input type="text" id="test-test_id"> 
<?php 
    if(isset($_GET["val"])){ 
    $sent = $_GET["val"]; 
    echo "<h2>".$sent."</h2>"; 
    } 
?> 
<script type="text/javascript"> 
$('#test-test_id').change(function() { 
     var myValue = $(this).val();        
     window.location = '?val=' + myValue; //redirect page with para ,here do redirect current page so not added file name .      
    }); 

更新代码,而无需刷新

$('#test-test_id').change(function() { 

     var myValue = $(this).val(); 
     $.get("",{val:myValue},function(data){ 
      $("body").html(data); 
     });    
    //you can try with many option eg. "$.post","$.get","$.ajax" 
    //But this function are not reload page so need to replace update data to current html 
    }); 
</script> 
+0

嗨大卫。是否可以在不刷新页面的情况下执行此操作?因为我在(#test-test_id)中的选择将变回默认值 – CloudSeph

+0

是的,你可以看更新回答@IvanCloud –

+0

哇。那完美的作品。谢谢。但我的选择仍然回到默认状态。例如,我的下拉列表包含男性和女性的数据。一旦我选择女性。下拉列表将返回到男性。我怎样才能防止呢? – CloudSeph

你想要做的是有点复杂,首先你必须做一个AJAX请求你来自哪里,客户端变量传递给服务器,这样的:

$.post('/', { variable: "your_value_here" }, function() { 
    alert('Variable passed'); 
}); 

这个简单的代码,在Javascript中取得发送POST请求的URL传递给函数作为第一个参数,在这种情况下,我们传递给$ .post同一页面。现在,在PHP中你必须处理POST请求:

session_start(); // We start a session where we'll set the value of variable. 
if(isset($_POST['variable'])) { 
    $_SESSION['your_var'] = $_POST['variable']; 
} else { 
    /* Your page code */ 
} 

您还可以在数据库中注册的变量,但如果它是一个临时变量,你可以注册它的会话。请记住,在使用$_SESSION全局变量之前,请在每个页面中使用session_start()

帮助文档: jQuery.post()PHP Sessions

+0

我想asker想打电话给页面本身。 – noob

+0

是的。我想在页面本身 – CloudSeph

+0

这是什么意思?如果您想在整个页面中创建整个脚本,请确保您能够完成此操作。我在编辑我的答案,告诉你如何做到这一点。 – Syncro