2013-10-19 102 views
10

我想使用jQuery/AJAX将某些值从JavaScript传递到PHP。我有以下“简化”代码,不知道我做错了什么。在StackOverflow中似乎有相当多的类似问题/答案,但他们都没有真正帮助。尝试使用AJAX将变量值从JavaScript传递到PHP

HTML:

<div> 
<a href="#" id="text-id">Send text</a> 
<textarea id="source1" name="source1" rows="5" cols="20"></textarea> 
<textarea id="source2" name="source2" rows="5" cols="20"></textarea> 
</div> 

JAVASCRIPT:

$("#text-id").click(function() { 
$.ajax({ 
type: 'post', 
url: 'text.php', 
data: {source1: "some text", source2: "some text 2"} 
}); 
}); 

PHP(text.php):

<?php 

$src1= $_POST['source1']; 
$src2= $_POST['source2'];  

echo $src1; 
echo $src2; 

?> 

问题:什么也没有发生......不errors..nothing 。我没有看到在PHP回显语句中显示的'source1'和'source2'的值。

+1

首先包括jquery文件 –

+0

已经存在...在HTML头。我只是没有在这里展示。 – Gandalf

+1

请给我们一个线索!发生了什么,或没有发生?你看到错误信息吗? – 2013-10-19 05:20:16

回答

10

您需要包括success handler在你的AJAX调用:

$("#text-id").on('click', function() { 
    $.ajax({ 
     type: 'post', 
     url: 'text.php', 
     data: { 
      source1: "some text", 
      source2: "some text 2" 
     }, 
     success: function(data) { 
      console.log(data); 
     } 
    }); 
}); 

,并在控制台中,您会收到:

some textsome text 2 

请确保这两个test.php和你的html源文件在同一个目录下。

+1

嗨,JavaScript控制台确实显示“一些textsome文本2”。但由于某种原因,我没有看到任何PHP回声语句。你能告诉我为什么? – Gandalf

+0

@Gandalf我不知道我理解你的问题。你想要发回PHP源代码? – hjpotter92

+0

是的......它应该做些什么,然后将控制权发送回JavaScript。至少这是我想要实现的。在这种情况下,“echo $ src1”语句没有做任何事情。我期待它用$ src1值填充页面。 – Gandalf

1
$("#text-id").click(function(e) {// because #text-id is an anchor tag so stop its default behaivour 
e.preventDefault(); 
$.ajax({ 
type: "POST",// see also here 
url: 'text.php',// and this path will be proper 
data: { 
     source1: "some text", 
     source2: "some text 2"} 
}).done(function(msg) 
     { 
     alert("Data Saved: " + msg);// see alert is come or not 
    }); 
}); 

参考ajax

+0

谢谢,但这没有帮助。 – Gandalf

+0

查看更新代码@Gandalf –