AJAX不发送所选选项的当前值

PHP代码


<?php

if(isset($_POST['data'])) {

$file_handle = fopen('my_file.json', 'w');

fwrite($file_handle, json_encode($_POST['data']));

fclose($file_handle);

}

?>

html


<h1 id="title" class="text-lg-center text-md-center text-sm-left mb-4">test 

title</h1>

<p class="lead text-lg-center text-md-center text-sm-left mb-4">test 

content</p>

<button id="test" type="button" class="btn btn-lg btn-block btn-outline- 

success">Publish List</button>

<div class="form-group">

<label for="exampleFormControlSelect1">Example select</label>

<select class="form-control" id="selectfont">

</select>

</div>

javascript


$(function () {

var font = 0;

var font_names = ["Montez","Lobster","Josefin Sans"];


$.each(font_names , function (index , value) {

    $('<option />' , {

        'value' : index,

        'text' : value

    })

    .css({'font-family' : font_names[index]})

    .appendTo("#selectfont");

});


$("#selectfont").change(function () {

    var font = $(this).val();

    $("p").css('font-family' , font_names[font]);

});


var htmldata = {

    'content_font_type': font_names[font],

    'content_font_size': parseFloat($("title").css('font-size'))

    };


$("#test").click( function(){

    $.ajax({

        method: "POST",

        url: "test.php",

        data: {data: htmldata},

        success: function(data) {

            alert(data);

        }

    });

});

});

所以我想问的是为什么在my_file.json中content_font_type和content_font_size没有变化,但是当我在$(“#selectfont”)。 alert中使用alert(


小唯快跑啊
浏览 187回答 1
1回答

慕码人2483693

您有两个问题:当#selectfont修改,你设置一个局部变量font,而不是全局变量,因为你重新声明它var font。摆脱var关键字。您正在设置htmldata页面首次加载的时间。您需要在用户单击按钮时进行设置,以便获取更新的值。您实际上根本不需要该font变量。你可以得到的值#selectfont,当你设置htmldata。$("#test").click( function(){&nbsp; &nbsp; var htmldata = {&nbsp; &nbsp; &nbsp; &nbsp; 'content_font_type': font_names[$("#selectfont").val()],&nbsp; &nbsp; &nbsp; &nbsp; 'content_font_size': parseFloat($("title").css('font-size'))&nbsp; &nbsp; };&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; method: "POST",&nbsp; &nbsp; &nbsp; &nbsp; url: "test.php",&nbsp; &nbsp; &nbsp; &nbsp; data: {data: htmldata},&nbsp; &nbsp; &nbsp; &nbsp; success: function(data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(data);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript