如何使用Ajax从JavaScript调用php函数?

问题描述 投票:0回答:2

在我的Wordpress网站中,我想创建一个包含所有标签的下拉菜单,但由于它有超过7.000,因此只需在用户点击后加载。我现在只能使用Ajax,我已经开始了,但还没有完成。

http://jsfiddle.net/7kf1r9vw/2/

  • 在这个小提琴中,点击后,这个javascript文件被加载:/echo/js/?js=hello%20world!
  • Fiddle中的第二个例子就是显示我的实际代码。我希望php funcion填充的结果仅在用户单击后启动。

但我不知道如何将其更改为PHP函数。此外,是否可以在输出中添加纯PHP脚本或仅将其嵌入文件中?

javascript php jquery ajax wordpress
2个回答
-1
投票

正如Draco18s所说,在你的情况下,Javascript在客户端执行,PHP在服务器端执行。

在这种情况下,您可以使用Ajax向服务器发出请求。

例如,如果您有以下html:

<select name="tag-dropdown" id="selectTags">
    <option value="#">Select an artist</option>
</select>

您可以使用Ajax向PHP脚本发出POST请求:

$( document ).ready(function() {
  $.ajax({ url: 'merge2.php',
      data: {operationName: "tagsNames"},
      type: 'post',
      success: function(output) {
            tagNamesres = JSON.parse(output);
            jQuery.each(tagNamesres, function(name, val) {
                                $("#selectTags").append('<option value="'+val+'">'+name+'</option>');
            });             
            }
  });
}); 

PHP脚本可以包含以下内容:

    <?php 
if (isset($_POST['operationName']) && !empty($_POST['operationName']) && $_POST["operationName"]=="tagsNames") {
    $resultarray = array();
    $resultarray["tagName1"] = "tagValue";
    $resultarray["tagName2"] = "tagValue2";
    echo json_encode($resultarray);
    return;
}
?>

为了从PHP函数返回一些内容,您需要打印或使用echo。这只是一个例子,所以你可以开始使用这个:)

有关Ajax请求如何工作的更多信息,请阅读此http://thisinterestsme.com/simple-ajax-request-example-jquery-php/


-1
投票

您的问题似乎是“如何从我的浏览器javascript代码调用服务器上的php函数”。在您的代码中,您具有以下功能,其中第一个参数是服务器端请求:

function getSuccessOutput() {
  getRequest(
      '/echo/js/?js=hello%20world!', // demo-only URL
       drawOutput,

  );
  return false;
}

要更改它以调用服务器php例程,您可以将'/echo/js/?js=hello%20world!'更改为您要执行的服务器上的URL:例如'/myPHPFolder/someRoutine.php'。结果将传递回您的req对象。

在您的初始html文件中(例如index.html,或者您开始​​流程的地方),在body标记上包含onload选项:

<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="yada yada yada">
    <meta name="author" content="you">
    <title>title for browser tab</title>
  </head>
  <body class="tutorial" onLoad="initPage()">
    <select id="optionList"></select>
  </body>
</html>

这告诉浏览器运行没有参数的“initPage()”函数。然后initPage()函数发出异步调用并加载您的数据,可能会将其保存到进程中的本地变量。

function initPage()
{
    $('#optionList').empty(); // this ensures that you don't duplicate the info in the select list.
    $.when($.get('/myPHPFolder/someRoutine.php').done(function(res) 
    {   // if of interest, save the results to a cookie or variable.
        // you could also include a check to see if the data has already been downloaded.
        // This is a 'happy path' example, which does not include error checking from the host
        // build the optionList select HTML element
        for (let each in res)
        {(function(_idx, _arr)
            {
             // append the correct value to the select list. 
             // this example is based on returning a JSON object with an 
             // element called "id" which has the value I want to display in the options list
            $('#optionList').append('<option value="'+_arr[_idx].id+'">' +_arr[_idx].id+'</option>');})(each, res);
        }
        // create a function to execute when the user selects a different buyer
        $('#buyer').on('change', function() { /* do something useful here */ });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.