【问题标题】:Calling a php script from javascript从 javascript 调用 php 脚本
【发布时间】:2014-06-28 00:47:41
【问题描述】:

我有一个服务器端 PHP 脚本,它连接到数据库并选择一些数据。这可以在单独的浏览器中使用,但我似乎无法从 HTML 中的脚本运行它。

我的代码如下:

   <html>
   <head>
   </head>
   <script>
   function myFunction() 
    {
 $.ajax({
    $.post("xxx.xxx.xxx.xxx:xxx/test.php")
    .done(function(data) {
    alert("Data Loaded: " + data);
    });
  }
  </script>
  <body>
  <button onclick="myFunction()">Get Sites</button>
  </body>

如有任何帮助,我们将不胜感激。

【问题讨论】:

  • 究竟是什么“不运行”?对于初学者,请放弃$.ajax({ ... });$.post$.ajax 的简写。
  • Learn how todebug JavaScript。您的代码在语法上无效。
  • 所以我的服务器端 php 在单独的浏览器中运行并给我输出但是当我尝试将它嵌入到 java 脚本中时我没有得到任何输出。

标签: javascript php jquery scripting


【解决方案1】:

看看这个页面http://api.jquery.com/jquery.post/ ajax() 和 post() 是两个不同的函数,你对它们的使用是错误的。 你有两种可能:

$.ajax({
    type: "POST",
    url: //here your script's url
    data: //here the data you want to send
    })
    .done(function( data ) {
    //data is the server answer
    });
$.post( yoururl,yourdata)
.done(function( data ) {
// data is the server answer
});

【讨论】:

  • 怎么回事? OP如何修复它?帮助OP。如果不再相关,请删除。
  • 什么是操作?我看不到你的问题
  • OP:“原始海报”(发布问题的人)。我要求您在回答中更加详细。解释如何他“使用它们是错误的”。仅仅说 OP 是错误的是不够的。还包括一个如何修复它的示例。
【解决方案2】:

ajax的圈子

HTML 代码

<form id="form">
<input type="text" value="5" id="id">
<span id="total"></span>
</form>

jquery 代码

$(function(){
    $('#form').change(function(){
        var id= $('#form #id').val(); // get value

        $.post("ajax/your_php_file.php",id:id},function(data){
                if(data.error=="OK"){ 
                    $('#total').empty().append(data.total);
                } else { 
                       alert(data.erreur);
                }
        },"json");
        return false;
    })
});

php 文件

require_once('conection.php'); // if you need a conection to database
$data = array(); // to put data inside this array
extract($_POST); // to convert a $_POST to a normal varible 
    if(isset($id) AND $id>0) { 
             $data['total']=7; //... your code
             $data['error']='OK';
    } else { 
       $data['error']="no id!";
    }
echo json_encode($data);

【讨论】:

  • 我希望这有助于指导 OP 找到答案,但您正在做出很多的假设。
【解决方案3】:

您可以使用此代码

function myFunction() 
{
  $.post( "xxx.xxx.xxx.xxx:xxx/test.php", function( data ) {
  alert("Data Loaded: " + data);
  });
}

【讨论】:

  • 这对 OP 有什么帮助?您建议的方法实际上是deprecated。 OP 使用.done() 是可行的方法。
猜你喜欢
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
  • 2016-03-02
  • 2017-09-25
  • 1970-01-01
相关资源
最近更新 更多